It’s pretty simple to manipulate cookies in JS, but there are a few gotchas. Browser incompatibilities naturally crop up, although somewhat differently than you might expect; some browsers are more permissive of the Wrong Thing than others, so you might blot your copybook and not notice until you hit cross-browser testing.
Motivation
Why would you want to manipulate cookies in JS? Here are some use cases:
- You’re dynamically generating a page, and need to retrieve user preference settings stored in cookies
- You’re logging a user into a system with an AJAX-y interface, and don’t want to do a page reload to set the session cookie
- You want to store some data on the client-side
Resources
Here are two articles that discuss JS cookie manipulation:
Gotchas
My major difficulties with this topic were caused by the fact that not all characters are legal within a cookie’s value; the value must be filtered through escape()
in the general case. (This is a point the normally reliable quirksmode overlooks.) It appears that FF and IE will escape the cookie value automatically when you manipulate document.cookie
, but Safari will not.
Here are revised versions of the quirksmode createCookie
and readCookie
functions which incorporate escaping/unescaping logic:
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+"="+escape(value)+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
}
return null;
}