Sometimes, we want to get all the cookies from the browser with JavaScript.
In this article, we’ll look at how to get all the cookies from the browser with JavaScript.
How to get all the cookies from the browser with JavaScript?
To get all the cookies from the browser with JavaScript, we can get them from the document.cookie
string.
For instance, we write
const c = document.cookie.split(";").reduce((ac, cv, i) => {
const [key, val] = cv.split("=");
return Object.assign(ac, { [key]: val });
}, {});
console.log(c);
to get the cookie string with document.cookie
.
Then we split the string by the semicolons and return an array of cookie strings.
Next, we call reduce
with a callback that splits the cv
string into the key
and val
strings with split
.
And we return an object that merges the { [key]: val }
object into the ac
object with Object.assign
.
Then c
is an object with all the cookies with the cookie keys as property keys and the corresponding values as values.
Conclusion
To get all the cookies from the browser with JavaScript, we can get them from the document.cookie
string.