Cannot set cookies in Javascript
I have a very simple line of code that set and read a cookie. I kept getting empty value for my cookie and have no understanding why. I have cookie enabled and know that cookies work on the browser.
<HTML>
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
document.cookie = "ding=dong";
</SCRIPT>
<script type="text/javascript">
alert(document.cookie);
</script>
</BODY>
</HTML>
Solution 1:
Recently I stumbled upon a similar issue. My script couldn't store a cookie in Chromium, although it worked well on all other major browsers. After some googling it turned out that Chrome ignores cookies from local pages. After I uploaded the page to remote server code magically started to work.
Solution 2:
I tried to save an cookie on Chrome and had the same error, that it would save. Although it did work in Firefox, so I asked an collegue and he suggested that I take away path and domain (I had name of cookie, value, expire, path amd domain) and all of a sudden it worked. So just to get the cookie to actually save in Chrome, you just need name, value and expire.
Hope it helps.
Example:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+";";
}