Home / Get all cookies with Javascript

Get all cookies with 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.