To look at the current cookies (in Chrome) of a website open the console and click on
Cookies. Then click to expand and click on the url. The current cookies should show on the right.
To get the cookies programmatically simply use
document.cookie. You can try this out in the console window.
You’ll see that it is a string of key-value pairs separated by semicolons.
To add a cookie you can manually add it by typing it into the cookie section of the console, but this isn’t very useful. To add one programatically simply use
document.cookie = "key=value" for example
document.cookie = "foo=foo" would add a cookie named foo with a value of “foo”.
As I stated earlier,
document.cookie will give you the cookies in string form separated by semicolons. So to retrieve a specific cookie you’ll have to use some string manipulation.
First, split by the name of the cookie plus “=”.
that will give you an array of two strings. All the cookies before “foo=” in the first element of the array and everything after “foo=” in the second element of the array. This will be where are value is. We can use
pop() to retrieve the last element in the array where are value you will be.
Unless the value is the last (which we can’t ever be sure if in the middle of execution), then we’ll need to split again. This time on “;” since that’s what separates the cookies. After this split, the value should be the first element fo the array that’s returned. With
shift() we can retrieve it. Let’s put his all together.
The above code should get you the value of any cookie if you replace “key” with the name of the cookie.
You can make cookies expire. This is useful for tokens that authenticate users. After they expire, the site logs the user out.
While before we simply did
document.cookie = "foo=foo", if we wanted
foo to expire then we would do this instead.
document.cookie = "foo=foo; expires=" + date.toGMTString()
date would be a date that you set. For example, if you wanted it to expire in 3 days you’d do this.
var date = new Date() date.setTime(date.getTime() + 3 * 24 * 60 * 60 * 1000) document.cookie = "foo=foo; expires=" + date.toGMTSTring()
This has been a quick-n-dirty guide on Browers cookies.