How to list all the cookies of the current page using JavaScript ?

In this article, we will learn how to get the list of all the cookies for the current page in JavaScript, along with understanding their implementation through the examples. The task is to retrieve the cookies stored in the current domain (We can not get all cookies due to security reasons). There are two methods to solve this problem which are discussed below.

Approach 1:

  • Access the cookies using document.cookie.
  • Use the .split() method to split them on “;” to get an array of cookies.
  • Traverse the array of cookies.
  • Append all cookies one by one in a string for print.

Example: This example implements the above approach.

Javascript
function getCookies() {
    let cookie = "username=Beginner;expires=Mon, 18 Dec 2023;path=/"; 
    let cookies = cookie.split(';');
    let ret = '';
    
    for (let i = 1; i <= cookies.length; i++) {
        ret += i + ' - ' + cookies[i - 1] + "\n";
    }

    return ret;
}

console.log(getCookies());

Output
1 - username=Beginner
2 - expires=Mon, 18 Dec 2023
3 - path=/

Approach 2:

  • Access the cookies using document.cookie.
  • Use the .split() method to split them on “;” to get an array of cookies.
  • Use the .reduce() method and access each cookie one by one.
  • To get the name and value of the cookie. For each cookie, split it on “=” using the .split() method and access the Name and Value from the cookie.
  • This method does the same thing as the previous method and returns the cookies as an object.

Example: This example implements the above approach.

Javascript
function getCookies() {
    let cookie = "username=Beginner;expires=Mon, 18 Dec 2023;path=/";

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

console.log(getCookies());

Output
{ username: 'Beginner', expires: 'Mon, 18 Dec 2023', path: '/' }

Approach 3:

  • Access the cookies using document.cookie.
  • Use the .split() method to split them on ; to get an array of cookies.
  • Use the map() method to create an array of key-value pairs for each cookie.
  • Transform the array of key-value pairs into an object using Object.fromEntries().

Example: Implementing the third approach

JavaScript
function getCookies() {
    let cookie = "username=Beginner;expires=Mon, 18 Dec 2023;path=/";
    
    let cookies = Object.fromEntries(
        cookie.split(';').map(cookie => {
            const [name, val] = cookie.split('=').map(c => c.trim());
            return [name, val];
        })
    );
    return cookies;
}
 
console.log(getCookies());

Output
{ username: 'Beginner', expires: 'Mon, 18 Dec 2023', path: '/' }




Contact Us