Open In App

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:



Example: This example implements the above approach.




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:

Example: This example implements the above approach.




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: '/' }

Article Tags :