Categories
Get all cookies with Javascript
Its very common that we all still use HTTP or HTTPS cookies for storing various data on visitor’s browser. But in HTML5 , you can use local storing various data . I’m talking about the old school for getting all the cookies using the Javascript . Here as we still have old browsers to take care of the cookies.
The jQuery Cookie plugin (http://plugins.jquery.com/project/Cookie) is useful for getting the value of cookies when you already know the name of the cookies you want to query from the browser, but provides no way to get a list of all the cookies that are set already.
The following Javascript 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;
}
var cookies = get_cookies_array();
for(var name in cookies) {
console.log( name + ” : ” + cookies[name] + “
” );
}
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 />” );
}
You can access cookie information in javascript using document.cookie function, but you will only be able to read the cookies that are on the same domain that the script is being run.