JavaScript, Duplicate Cookies and Paths

April 22, 2005

JavaScript, Duplicate Cookies and Paths

While the new SoftwareMedia.com doesn't require JavaScript, it does use it in a few places for enhanced functionality, such as the Specials marquee and the expanding categories on the right side. For these enhancements, it uses cookies to remember the state of things. This ensures that no matter where a visitor navigates throughout the site, if he/she has turned the marquee off or expanded the hardware category, it will stay that way.

Only it wasn't consistent... sometimes it would remember your preferences, sometimes it wouldn't. Doing some casual JavaScript debugging revealed that there were duplicate entries in document.cookies. As it turns out—this should have been a no-brainer—when you set a cookie in JavaScript, if you don't specifiy a path, it will default to the path of the current page.

Suppose a script on a weppage (http://foo.bar/path/) sets a cookie via JavaScript:

document.cookie = "selectedCategory=hardware";

If the visitor then navigates to the home page (http://foo.bar/) , scripts on that page will be unable to access the "selectedCategory" cookie. If a script then sets the cookie to "software", when the user navigates to the original page (http://foo.bar/path/), there will be two occurrences of the "selectedCategory" cookie in the document.cookies object and scripts will have no way of knowing which one is the correct one.

Moral of the story: Always specify a path when setting cookies via JavaScript.

Posted by jon at April 22, 2005 2:58 PM

Comments

Post a comment









Remember personal info?