document.cookie = "mycookiename=value; expires=some gmt date time; path=thepath; domain=the domain";
Therefore, if we wanted to set a session only cookie, we can set something like this:
document.cookie = "mtracker=somevalue; expires=0; path=/";
It looks like the PHP equivalent isn’t it?
The above code snippet works flawlessly in Firefox and Google Chrome. However, it expires immediately as soon as it is set in Internet Explorer. My Google Kung-Fu didn’t work this time and ask a colleague to help debug the issue.
The problem was that Internet explorer has different interpretation with the
expires parameter. Instead of giving ZERO to expire, we will leave it out completely. This should be the syntax in most cases.
document.cookie = "mtracker=somevalue; path=/";
That’s it! Be gentle to our friend IE.
Thanks–I know this is an old post but it was very helpful. Couldn’t get it to work in IE to save my life and this fixed it.
Excellent!!!!!!!!!!!!!!!!!!!!! I found a different solution for the IE problem before but it was far more complicated and it was written by someone else. This is just one line. Excellent!!!!!!!
My code needs to go on a diet and you’re definitely helping.
If you want to support MSIE 9 and your script does both cookie setting and DOM manipulation (such as calling removeChild), set the cookie before doing the DOM manipulation. Otherwise, MSIE 9 might not keep the cookie any longer than a fraction of a second; this appears to be a bug in MSIE 9. For more details, download the Web Adjuster source code and search it for “works around a bug in MSIE 9”.
Does excluding the expires parameter work correctly in Chrome/Firefox as well or do you need to implement both depending on the browser?
As far as I know, it works and it is still live in production without issues.