Cookies are small text files stored by Web browsers on the users machines. They are used to store information about the users access to sites. Each server (domain) gets it's own file in which are the cookies for that site. Actually more advanced browsers use a cut-down database to store cookies but the principle is the same - text on the users' disk. Cookies allow a website to record information about the user, their preferences/settings, which pages the user has seen etc..
Create a cookie
JavaScript cannot write directly to files (that would be a major security risk). Instead cookies are treated as part of the Web page and then the browser stores them how it wants to. To create a cookie:
document.cookie='username=fred;';
As each cookie has a name (the bit before the equals sign) you can add more than one:
document.cookie='junk=jhg;';
document.cookie='username=fred;';
document.cookie='llll=aedc;';
The cookies are stored as separate files but the browser knows they belong to this domain or page.
Note that there is a semi-colon at the end of each cookie. Put those three lines into a SCRIPT element and load the page in a browser (you should see a blank page). Go to wherever your browser keeps it's cookies (normally accessible through the settings dialog). Look at the most recent cookies to see your three.
Reading cookies
You can also read the data back
var cookieText=document.cookie;
alert(cookieText);
If there are multiple cookies they should appear as a list separated by semi-colons. Try it with the above example cookies or your own.
If you know the name of the cookie you want the value for (here it is username) you can find the start and end of the cookie to extract it:
var cookieStart=document.cookie.indexOf('username'+"=");
var cookieEnd=document.cookie.indexOf(';', cookieStart);
var thisCookie=document.cookie.substring(cookieStart,cookieEnd);
alert(thisCookie);
The method indexOf finds the position of a string inside another. Here it is finding the cookie name inside the string of cookies (the = is included in the search just in case the cookie name is duplicated in the content of another cookie). In the second line once you have the start of the cookie you can look for the end of it by examining the text from the start point. The end of each cookie will be marked by a semi-colon so that is what you look for.
The third line finally extracts the cookie text (both name and value). Starting and ending with the two positions found in the previous lines.
The fourth is just to show you it worked. You could now split the name and value but it is quicker to amend the above code to do that in one step.
Reading just the value
Often you will just want the value of the named cookie. Amend the line to start the reading of the cookie after the equals sign. You know the length of the cookie name so add that (plus one for the equals sign) to the start point of the substring:
var cookieStart=document.cookie.indexOf('username'+"=");
var cookieEnd=document.cookie.indexOf(';', cookieStart);
var thisCookie=document.cookie.substring(cookieStart+9,cookieEnd);
alert(thisCookie);
You should now have just the value and so can use it in your code.
Expiry
Unless you say otherwise a cookie will expire (be deleted or ignored) once you close the browser (or tab). If you want a longer expiry (for example to remember someone when they come back the next day) you have to set it:
var cookieDate=new Date();
cookieDate.setDate(cookieDate.getDate()+14);
document.cookie='username=fred; expires='+cookieDate;
You could do that with just one variable but this way makes it clearer what is happening:
- the first line creates a new date variable/object and by default puts the current date into it
- then 14 is added to the day of the month part of the date
- the cookie is written with the expiry two weeks from now
What if the cookie does not exist?
In regard to the reading back of cookies you would want to add some IF statements to the above code:
var cookieStart=document.cookie.indexOf('username'+"=");
if (cookieStart!=-1){
var cookieEnd=document.cookie.indexOf(';', cookieStart);
var thisCookie=document.cookie.substring(cookieStart,cookieEnd);
alert(thisCookie);
} else {
alert('Cookie not found');
}
Browser compatibility
Some browsers will not place a semi-colon after the final cookie in a list of the cookies for the page (document.cookie). When extracting a single cookie as shown above JavaScript will not correctly find the end of the last one if there is no ";". So check to see if it managed with another IF statement:
var cookieStart=document.cookie.indexOf('username'+"=");
if (cookieStart!=-1){
var cookieEnd=document.cookie.indexOf(';', cookieStart);
if (cookieEnd!=-1){
cookieEnd=document.cookie.length;
}
var thisCookie=document.cookie.substring(cookieStart,cookieEnd);
alert(thisCookie);
} else {
alert('Cookie not found');
}
The new IF will set the end of the substring to the end of the whole document.cookie string if there is no semi-colon.




