Is there any way to, with help of Javascript, list all cookies associated with the current page? That is, if I don\'t know the names of the cookies but want to retrieve all
Some cookies, such as referrer urls, have =
in them. As a result, simply splitting on =
will cause irregular results, and the previous answers here will breakdown over time (or immediately depending on your depth of use).
This takes only the first instance of the equals sign. It returns an object with the cookie's key value pairs.
// Returns an object of key value pairs for this page's cookies
function getPageCookies(){
// cookie is a string containing a semicolon-separated list, this split puts it into an array
var cookieArr = document.cookie.split(";");
// This object will hold all of the key value pairs
var cookieObj = {};
// Iterate the array of flat cookies to get their key value pair
for(var i = 0; i < cookieArr.length; i++){
// Remove the standardized whitespace
var cookieSeg = cookieArr[i].trim();
// Index of the split between key and value
var firstEq = cookieSeg.indexOf("=");
// Assignments
var name = cookieSeg.substr(0,firstEq);
var value = cookieSeg.substr(firstEq+1);
cookieObj[name] = value;
}
return cookieObj;
}