Setting Session Only Cookie via JavaScript

So you’re pretty good at cookies in PHP, then you suddenly wanted to manage cookies via JavaScript. Few days ago, I got a chance to work on cookies and JavaScript but as usual, our beloved Internet Explorer blocks my way.

PHP Cookies and JavaScript Cookies

We all know that in PHP, to set a session only cookie, all you need to do is leave the expire parameter blank or set it to ZERO (0). Of course we always need to set the path to “/” in most cases. However, it is quite different when it comes to JavaScript.

The syntax for setting up cookie in JavaScript is simple.

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?

Internet Explorer

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.

This entry was posted in Internet Explorer, JavaScript and tagged , , . Bookmark the permalink.

6 Responses to Setting Session Only Cookie via JavaScript

  1. Ben Steed says:

    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.

  2. Gemma D Lou says:

    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.

  3. 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”.

  4. Mukul says:

    Awesome…..

  5. Josh says:

    Does excluding the expires parameter work correctly in Chrome/Firefox as well or do you need to implement both depending on the browser?

  6. lysender says:

    As far as I know, it works and it is still live in production without issues.

Leave a Reply

Your email address will not be published. Required fields are marked *