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.