Monday, July 30, 2007

Accessing Cookies from Javascript

I recently had occasion to access the contents of a cookie stored on the clients computer using Javascript. I found the following javascript function very handy. I wander if something similar is built into javascript:

function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}

No comments: