Categories
JavaScript Answers

How to list all cookies for the current page with JavaScript?

Spread the love

Sometimes, we want to list all cookies for the current page with JavaScript.

In this article, we’ll look at how to list all cookies for the current page with JavaScript.

How to list all cookies for the current page with JavaScript?

To list all cookies for the current page with JavaScript, we can get them from the document.cookies string.

For instance, we write

const cookiesObj = document.cookie.split(";").reduce((cookies, cookie) => {
  const [name, value] = cookie.split("=").map((c) => c.trim());
  cookies[name] = value;
  return cookies;
}, {});

to call document.cookies.split to split the string by the semicolon and return the array of cookie strings.

Then we call reduce with a callback that splits each string by the '=' string and then call map with a callback to trim the start and end of the strings.

We then get the name and value from the returned array.

Next, we add the name property to cookies and set it to value.

And then we return cookies.

The final cookies object returned by reduce is assigned to cookiesObj.

Conclusion

To list all cookies for the current page with JavaScript, we can get them from the document.cookies string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *