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

Comments

February 16. 2010 04:07

Jeremy

Thanks!

Worked fine for me.

Jeremy

March 3. 2010 06:30

Z Chacka

Would it be ok to call this method only once and access cookies anywhere in the page? Or should I call it every time I am about to use a cookie on the page?

I wonder if it can be kept in an included external js script file, and then everywhere else simply use the cookies['cookieName'] approach to access cookies.

Z Chacka

Don't Post SPAM

If you are posting a commment just to get a link, don't waste your time!

I have a sophisticated comment moderation system in place, and your comment will not be posted.

Add comment




biuquote
  • Comment
  • Preview
Loading