How can I list all cookies for the current page with Javascript?

JavascriptCookies

Javascript Problem Overview


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 the information they contain.

Javascript Solutions


Solution 1 - Javascript

You can list cookies for current domain:

function listCookies() {
    var theCookies = document.cookie.split(';');
    var aString = '';
    for (var i = 1 ; i <= theCookies.length; i++) {
        aString += i + ' ' + theCookies[i-1] + "\n";
    }
    return aString;
}

But you cannot list cookies for other domains for security reasons

Solution 2 - Javascript

var x = document.cookie; 
window.alert(x);

This displays every cookie the current site has access to. If you for example have created two cookies "username=Frankenstein" and "username=Dracula", these two lines of code will display "username=Frankenstein; username=Dracula". However, information such as expiry date will not be shown.

Solution 3 - Javascript

Many people have already mentioned that document.cookie gets you all the cookies (except http-only ones).

I'll just add a snippet to keep up with the times.

document.cookie.split(';').reduce((cookies, cookie) => {
  const [ name, value ] = cookie.split('=').map(c => c.trim());
  cookies[name] = value;
  return cookies;
}, {});

The snippet will return an object with cookie names as the keys with cookie values as the values.

Slightly different syntax:

document.cookie.split(';').reduce((cookies, cookie) => {
  const [ name, value ] = cookie.split('=').map(c => c.trim());
  return { ...cookies, [name]: value };
}, {});

Edit: Someone correctly pointed out that you'll face issues if your cookie key or value has an = in it. Maybe consider using escape sequences to mitigate this?

Solution 4 - Javascript

For just quickly viewing the cookies on any particular page, I keep a favorites-bar "Cookies" shortcut with the URL set to:

javascript:window.alert(document.cookie.split(';').join(';\r\n'));

Solution 5 - Javascript

No.

The only API browsers give you for handling cookies is getting and setting them via key-value pairs. All browsers handle cookies by domain name only.

Accessing all cookies for current domain is done via document.cookie.

Solution 6 - Javascript

function listCookies() {
    let cookies = document.cookie.split(';')
    cookies.map((cookie, n) => console.log(`${n}:`, decodeURIComponent(cookie)))
}

function findCookie(e) {
  let cookies = document.cookie.split(';')
  cookies.map((cookie, n) => cookie.includes(e) && console.log(decodeURIComponent(cookie), n))
}

This is specifically for the window you're in. Tried to keep it clean and concise.

Solution 7 - Javascript

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;
}

Solution 8 - Javascript

No there isn't. You can only read information associated with the current domain.

Solution 9 - Javascript

I found this code on https://electrictoolbox.com/javascript-get-all-cookies/, which worked for me better than the other solutions:

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSpeldosaView Question on Stackoverflow
Solution 1 - JavascriptDixonDView Answer on Stackoverflow
Solution 2 - JavascriptSpeldosaView Answer on Stackoverflow
Solution 3 - JavascriptJayant BhawalView Answer on Stackoverflow
Solution 4 - JavascriptPaul BishopView Answer on Stackoverflow
Solution 5 - JavascriptYuval AdamView Answer on Stackoverflow
Solution 6 - JavascriptFofasterView Answer on Stackoverflow
Solution 7 - JavascriptTravis JView Answer on Stackoverflow
Solution 8 - Javascripttur1ngView Answer on Stackoverflow
Solution 9 - JavascriptElyView Answer on Stackoverflow