3

I'm trying to use cookies for a project I have, so I looked for a method to create them using JavaScript and found, looking on some websites, a function (it looks like a function) called document.cookie. Using the following code on the console:

var value = "testCookie";
document.cookie = "testCookie=" + value + ";";
alert(document.cookie);

The alert, which should contain the cookie, appears blank, as if the cookie had not been created. What am I doing wrong? If you can tell me, I will be immensely grateful!

Davi Koala
  • 33
  • 5
  • 2
    In Chrome, for cookies to work, your page needs to be served with the `http(s)://` protocol, it won't work with `file:///C:/...`. Either use a server (local or remote), or use another browser, like Firefox, which does allow that – blex Dec 17 '20 at 22:06
  • 1
    @blex Firefox will reject the cookie whenever you close the tab. – Danny Dec 17 '20 at 22:22
  • 1
    @SamuelEbert Yes, that's true. Depending on the use case, it can be enough for simple _same-tab_ testing, but a server will be more convenient – blex Dec 17 '20 at 22:29

2 Answers2

3

There is nothing wrong with your code. It works. You can test it right on this page by hitting F12 to open a console in Chrome, pasting your code in it, and hitting ENTER.

enter image description here

Also, after doing that, you can click on the "LOCK" symbol to the left of the "https://stackoverflow.com/questions/65348915/javascript-cookie-is-not-being-created" address in the address bar => Cookies => Stackoverflow => Cookies enter image description here

Now, in order to set cookies, you need to serve your static (HTML+JS) files from a web server, even when you want to do it locally. Just opening a file from the disk won't let you set cookies.

The easiest way to do it is to install Node JS and use one of many web servers available there, like in this example https://stackoverflow.com/a/54690795/9805867

IvanD
  • 2,728
  • 14
  • 26
3

Your code is correct (although + ";" is redundant). As mentioned by @blex, cookies set on a file:/// URL will be rejected. You will need to serve the page from a webserver. You can also use JSFiddle.

Danny
  • 669
  • 9
  • 20