Cookies are small text files stored by Web browsers on the users machines. They are used to store information about the users and their 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 - data on the users' disk where they can get at it. Cookies allow a Web site to record information about the user, their preferences/settings, which pages the user has seen etc..

Be aware that browsers can refuse cookies depending on settings.  Also browsers may not store cookies from the local host so to test them properly your pages will need to be on a server.  If you have access to a full server try all this on it.  If not you will need to just read it through and come back later.

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 make a page called cookies.html and put this inside the script element before uploading it to the server:

document.cookie='username=fred;';

The text inside quotes is the cookie.  It starts with the name of the cookie and then the value to be stored.  If the name already exists the value will be changed.  If the name does not exist it is created.  After the value is a semi-colon because you can have more data in a cookie and the semi-colon separates individual parts.  To add more add these lines after the first one:

document.cookie='junk=jhg;';
document.cookie='llll=aedc;';

Read a cookie

var myCookie=document.cookie;

If you wanted to retrieve just one cookie you would use indexOf and substring to extract it from the cookies which are now stored in myCookie.

Expiry

Unless you say otherwise a cookie may 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.  First you would create a date, add some time or days to it and then include it in the cookie. Add these to cookie.html :

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:

  1. the first line creates a new date variable/object and by default puts the current date into it
  2. then 14 is added to the day of the month part of the date
  3. the cookie is written with the expiry two weeks from now

What if the cookie does not exist?

When reading cookies you would want to add some if statements to the code.  This will extract just the username data (add it):

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');
}

Try it and then change the first line to look for password instead of username.  You should see a different message.

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 you can check to see if it managed by adding another if statement (no need to do this now):

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.