Accessing Cookie with Javascript
The document.cookie Property is available in DOM for accessing cookie values in javascript. This Property returns all of the cookies in a long semicolon separated string. For example:
cookie1=value1; cookie2=value2; cookie3=value3; ...
There is no way of accessing individual cookie values like we access Request variables on the server side. You must extract the required cookie value from one long string. It can be easily done with a few lines of code, but if you like the way things work on the server side, here is a small helper Javascript function I wrote to prepare a dictionary with all cookie values. Now instead of trying to extract value from a long string, you can use the following code:
var cookies = getCookies();
var value1 = cookies["cookieName"];
//Now value1 holds the value of cookie "cookieName"
Makes things easier especially when multiple cookies are in use. Here is the helper function that prepares a dictionary with all available cookies and values:
function getCookies()
{
var cks = new Object();
var ckList = document.cookie.split("; ");
for (var i=0; i < ckList.length; i++)
{
var ck = ckList[i].split("=");
cks[ck[0]] = unescape(ck[1]);
}
return cks;
}
This code has been used in several places without any problems. If you encounter any issue, please post a comment.
Posted on February 11, 2010 09:50 by
Haider