You can access the cookies for a particular page by referencing the
cookie property of the document object. i.e. document.cookie
. For example, on this page it might look something like this:
"__amplitudeDeviceID=5a80df15-5e17-4d9c-96ad-d7cdd5c9a392; hn-cookie-username=ckgao2eh000003h64tsqx0dhx; __gacid=cee040d8-3c13-4da6-8f56-f58e54c476f3; __acquisitionSource=blog-footer; _hjid=c1c759b9-2f9a-45b2-a90f-8dd04549e76e; _hjIncludedInPageviewSample=1; _hjAbsoluteSessionInProgress=1; __acquisitionURL=https://hashnode.com; hn-user=5da7008dc6d94e4b3b607a4b; __hncsrf=-HezIudC06Uch767NzYTFC7K
To set a new cookie you simply assign a new string to document.cookie
.
For example, to create a new cookie with a name of user
and a value of james
:
document.cookie = 'user=james';
It might look like you’re going to remove all the other cookies by doing this but the above will just set a new cookie with the name of user
and a value of james
. If there are any other cookies stored on the page they'll be preserved.
Cookies are stored in a string on the document.cookie
property so getting a particular cookie value requires a bit of work.
If you want to get a particular cookie value you need to manipulate the cookie string.
One possibility is by splitting it into an array with a semi-colon as the delimiter.
document.cookie.split(';')
You will still need to do a bit of work to get the value of a particular cookie (like splitting each string in the array further by its =
symbol , then search for the name of the cookie).
Alternatively, you can reduce the split cookie array to a single object.
Here's one approach of doing that:
document.cookie
.split(';')
.map(cookie => cookie.split('='))
.reduce((accumulator, [key, value]) => ({ ...accumulator, [key.trim()]: decodeURIComponent(value)
}), {});
Running the above code on this page would put the cookie string into an object a bit like this:
{
__amplitudeDeviceID: "5a80df15-5e17-4d9c-96ad-d7cdd5c9a392",
hn-cookie-username: "ckgao2eh000003h64tsqx0dhx",
__gacid: "cee040d8-3c13-4da6-8f56-f58e54c476f3",
__acquisitionSource: "blog-footer",
_hjid: "c1c759b9-2f9a-45b2-a90f-8dd04549e76e", …
}
Follow me on Twitter for more tutorials 👍