Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to list all the cookies of the current page using JavaScript...

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

RELATED ARTICLES

Most Popular

Recent Comments