Thursday, July 4, 2024
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: '/' }

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments