Get all cookies with JavascriptGet all cookies with Javascript

Posted June 12th, 2009 in Javascript

In my last jQuery post I looked at how to set, get and clear cookies with jQuery and now look at how to get a list of all the cookies that have been set. This is not jQuery specific and will work with just regular Javascript.

The jQuery Cookie plugin (http://plugins.jquery.com/project/Cookie) is useful for getting the value of a cookie when you already know the name of the cookie you want to query, but provides no way to get a list of all the cookies that are set.

The following function loads them all into an associative array with the cookie name as the index and the cookie value as the value:

function get_cookies_array() {

    var cookies = { };

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
        }
    }

    return cookies;
   
}

You could then get the cookies and write them out into the document like so:

var cookies = get_cookies_array();
for(var name in cookies) {
  document.write( name + " : " + cookies[name] + "<br />" );
}

Note that the "name_value[0] = name_value[0].replace(/^ /, '');" line removes leading space from the cookie name which will be present for the second and subsequent cookies.

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus