102

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.

Ben Zotto
  • 70,108
  • 23
  • 141
  • 204
Speldosa
  • 1,900
  • 5
  • 21
  • 36
  • Please clarify if by "certain page", you mean "the page the user is currently on". DixonD's answer is spot on for current-page cookies. All other domains are offlimits for security reasons. – Ben Zotto Aug 03 '10 at 21:15
  • 1
    Yes. I'm talking about the page the user is currently on. – Speldosa Aug 03 '10 at 21:19
  • 1
    OK. I edited the title and question to reflect that. DixonD's answer is appropriate here. – Ben Zotto Aug 03 '10 at 22:04
  • Note that this is something that you actually probably want to disable with `HttpOnly`. This is because it makes XSS attacks a lot less powerful. – Flimm Jan 13 '16 at 13:29

11 Answers11

118

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

DixonD
  • 6,557
  • 5
  • 31
  • 52
  • 1
    I must have been clumsy in my description of the problem. What I wanted to do was to get a list of all the cookies created by any html-documents in the same catalogue. In the html-document I simply added the following code: var x = document.cookie; window.alert(x); ...and I could see all the cookies I had created. Sorry if I expressed myself in an unclear way. Thanks for all the quick answers though. I already like this site :) – Speldosa Aug 03 '10 at 22:17
  • 11
    Also this does not work when the cookie has been set value ```httpOnly=true```. – Risto Novik Sep 04 '13 at 12:04
  • 2
    Nicer output via `aString += i + ' ' + decodeURIComponent(theCookies[i-1]) + "\n";` – Mark Rajcok Sep 03 '14 at 21:19
28

Experimental Spec (poor browser support as of Apr 2023, use 2022 answer):

const cookies = await cookieStore.getAll()
// Then...
Object.fromEntries(cookies.map(({name, value}) => [name, value]))
// OR
cookies.reduce((cs, c) => ({...cs, [c.name]: c.value}), {})

Read more here: https://developer.mozilla.org/en-US/docs/Web/API/CookieStore/getAll

Updated for 2022

tl;dr - Here's a one liner:

Object.fromEntries(document.cookie.split('; ').map(c => c.split('=')))

Note: You cannot get http-only cookies in browser code.

Here's the same thing, explained:

const getCookieMap = () => {
  // Cookies are generally separated by a "; "
  // https://stackoverflow.com/a/4843598/2968465
  const cookieList = document.cookie.split('; ');

  // A key-value pair in the cookie list is separated by a "="
  // We pass a function to cookieList.map that will return
  // an array of tuples, like [key, value]
  const cookieToObjEntry = cookie => cookie.split('=')
  const cookieEntries = cookieList.map(cookieToObjEntry)

  // Such an array can be passed to Object.fromEntries to
  // obtain an object with all cookie key-value pairs as
  // the keys and values of an object
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries
  return Object.fromEntries(cookieEntries)

  // So, for a cookies stored as "c1=v1; c2=v2", you'll get
  // an object like `{c1: v1, c2: v2}`
}

Older answers

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?

Jayant Bhawal
  • 2,044
  • 2
  • 31
  • 32
22
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.

Speldosa
  • 1,900
  • 5
  • 21
  • 36
  • 2
    This doesn't work if you have set the cookie with `httpOnly`, which is recommended, since it helps to diminish the negative consequences of an XSS attack. – Flimm Jan 13 '16 at 13:27
  • Nothing on the browser side can let you do that, Flimm. This is a basic bit of security, so it does not diminish the value of the answer. – oligofren May 24 '23 at 12:38
4

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'));
Paul Bishop
  • 49
  • 1
  • 1
2

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.

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
  • 1
    This doesn't work if you have set the cookie with httpOnly, which is recommended, since it helps to diminish the negative consequences of an XSS attack. – Flimm Jan 13 '16 at 13:28
2

Besides document.cookie you can use the cookie store API, mainly getAll() method of CookieStore.

Here's a simple example, you can do something like:

const cookies = await cookieStore.getAll(); //Array of all available cookie info
cookies.forEach(c => console.log(`${c.name}: ${c.value}`));

Please note that this API is still experimental and not supported by all browsers (e.g. Firefox) as of the time of writing this.

Mr.Cat
  • 151
  • 1
  • 10
1
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.

Fofaster
  • 127
  • 7
1

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;
}
Travis J
  • 81,153
  • 41
  • 202
  • 273
1

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;
}
Ely
  • 8,259
  • 1
  • 54
  • 67
0

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

tur1ng
  • 3,139
  • 5
  • 24
  • 31
  • Damn :) Ok...Follow up questions: 1. Is there any way to check if a specific cookie exists (with a certain name that you know)? 2. Is there any kind of manual for JavaScript where for example the document.cookie class is desribed in detail? – Speldosa Aug 03 '10 at 21:14
  • I think so too. However, I would like to get hold of something equivalent of this: http://download.oracle.com/javase/1.4.2/docs/api/overview-summary.html – Speldosa Aug 03 '10 at 21:22
0

Simple solution that converts all Cookies to JSON:

    let output = [];
    document.cookie.split(/\s*;\s*/).forEach((pair) => {
      var name = decodeURIComponent(pair.substring(0, pair.indexOf('=')));
      var value = decodeURIComponent(pair.substring(pair.indexOf('=') + 1));
      output.push({ key: name, val: value });
    });
Wipf
  • 1