Open In App

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

Last Updated : 13 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cookies are small pieces of data stored by websites on your browser to remember information about your visit, such as login status, preferences, or other settings. In JavaScript, you can easily retrieve cookies stored by the current domain using document.cookie. However, due to security reasons, you can only access cookies set by the current domain and not those set by other domains.

We will learn how to get a list of all cookies for the current page in JavaScript through various approaches. We will explore three different methods to accomplish this task and provide examples to help you understand each approach.

Approach 1: Using document.cookie and .split()

In this approach, we will access cookies using document.cookie, which returns a string containing all cookies for the current domain. We then split this string on ";" to get an array of individual cookies, traverse through the array, and append each cookie to a string for display.

Steps:

  • Access the cookies using document.cookie.
  • Use the .split(";") method to split the cookies string into an array.
  • Traverse the array to access each cookie.
  • Append each cookie to a string for printing.

Example: This example implements the above approach.

JavaScript
function getCookies() {
    let cookie = "username=geeks;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=geeks
2 - expires=Mon, 18 Dec 2023
3 - path=/

Approach 2: Using document.cookie with .reduce()

This approach also starts by accessing the cookies using document.cookie and splitting them into an array using .split(";"). However, instead of manually appending the cookies, we use the .reduce() method to transform the cookies into a more structured format, such as an object with cookie names as keys and values as values.

  • 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=geeks;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: 'geeks', expires: 'Mon, 18 Dec 2023', path: '/' }

Approach 3: Using document.cookie with .map() and Object.fromEntries()

In this approach, we first access the cookies using document.cookie and split them into an array. We then use .map() to create an array of key-value pairs for each cookie. Finally, we transform this array into an object using Object.fromEntries().

  • 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=geeks;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: 'geeks', expires: 'Mon, 18 Dec 2023', path: '/' }

Each approach provides a different way to handle and display cookies, giving you the flexibility to choose the method that best fits your needs.


Next Article

Similar Reads