Path // www.yourhtmlsource.comJavaScript → COOKIES

Cookies


Cookies are the name given to the small text files your browser stores on your computer, which contain information relevant to the sites you have visited in the past. Using JavaScript you can write to these text files and then extract data from them whenever your reader returns to your site.

Clock This page was last updated on 2012-08-21



Why we use Cookies

Cookies are necessary because the HTTP protocol that is used to transfer webpages around the web is state-less. This means that web servers cannot remember information about users throughout their travels, and so everyone becomes anonymous. If you ever return to a site you have visited previously, you are treated as if it was your first visit.

This is especially unsatisfactory for sites which ask their users to log in — if you leave and return just a few minutes later, you'll have to log in again. The server doesn't remember anything about your visit or your preferred settings. So, cookies were invented to give memory, of a sort, to web servers.

Structure of a Cookie

Cookies are no more than simple text files — usually found in your browser cache, or ‘Temporary Internet files’ — which contain one or more entries. Each entry is made up of

  1. A name-value pair which stores whatever data you want to save.
  2. An expiry date, after which time the entry will be deleted.
  3. The web domain and path that the entry should be associated with.

You can use JavaScript to read or write a new entry to the cookie file. The process of creating an entry is often referred to as ‘writing a cookie’, but this is misleading. The cookie is the text file which contains all of your entries, while the individual entries themselves hold the data. Each domain name on the web can have a cookie file associated with it, and each cookie can hold multiple entries.

When you request a file from a server that you have used previously, the data in the relevant cookie is sent to the server along with your request. This way, server-side scripts, such as those written in Perl or » PHP, can read your cookie and figure out whether you have permission to view a certain page, for instance. Cookies can also be used for somewhat more malicious purposes, usually by advertising companies to track your behaviour online. Most modern browsers include good measures that allow you to block cookies from certain sites, so which sites you disclose information to is now at your discretion.

The name-value pair part of the entry is very similar to declaring a variable — when you want to retrieve information you ask for the value that is associated with a name that you provide. The expiry date is expressed in an unfriendly UTC format; though fortunately there are methods for generating a suitable date. If a date is not set, the entry is deleted when you close your browser.

The domain and path that you associate your cookie with have to be part of the same domain that your site belongs to. For instance, I can set my cookie to be active for www.yourhtmlsource.com, the default; or to yourhtmlsource.com, which will cover any and all subdomains I set up for the site. I cannot, however, set it to yahoo.com, for obvious security reasons. Using the path you can restrict a cookie to be valid for only a certain directory. Usually you'll want it to be available to any page in the domain, so this is set to /, the root directory.

Setting, Reading and Erasing Cookies

The document has an object in JavaScript called document.cookie, which is used to read and retrieve cookie data. It is a repository of Strings (though not an array). You can create new entries, read out an existing name-value pair, or erase an entry through JavaScript. To create a cookie for my site, I write

document.cookie = 
  "testvalue1=Yes; expires=Fri, 13 Jul 2004 05:28:21 UTC; path=/";

The whole entry is supplied as one quoted String with segments set apart with semicolons — first the name-value pair, then the expiry date in the correct format, and finally the path. This syntax is fixed, and you shouldn't go rearranging the elements. Write this entry now. To test out the cookie's contents, we can use a simple script like

alert(document.cookie);

Which will yield this result. You may see another value in there too, which is used by our Stylesheet-switcher. Now we can write another entry to the cookie, using a different name, as so:

document.cookie = 
  "testvalue2=Nah; expires=Fri, 13 Jul 2004 05:28:21 UTC; path=/";

Checking on the cookie's contents now, we can see that our first value is still in there. Had we used the same name, the first value would've been overwritten; but since we used a different name, the new entry has been added in with the first.

Erasing cookie entries is easy — just set a new value and give an expiry date before today, as in

document.cookie = 
  "testvalue2=Whatever; expires=Fri, 13 Jul 2001 05:28:21 UTC; path=/";

You can also give the entry an expiry date of -1, and it will be erased immediately. Erase test values 1 and 2 now, if you have the heart.

Convenient Scripts

To easily tinker with cookies ourselves, we'll be using some great scripts which were originally coded by » Scott Andrew. They'll take much of the pain out of the process; especially reading the values out of a cookie, which is a bit complicated. Here are the functions:

function createCookie(name, value, days)
{
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}

function eraseCookie(name)
{
  createCookie(name, "", -1);
}

These are some nicely coded scripts, and don't require too much explanation. The function we use to create cookies takes three arguments, which make up the name-value pair and the amount of days to retain the cookie. The last argument is converted into a valid date by adding its value in hours to the current time before being annexed into the line which creates the cookie.

The cookie reading function is the most difficult one here. First it splits the available cookie String (what we've been reading out in the alert earlier on this page) at every occurrence of the separating semicolon. This creates a new array, with each index holding an entry pair. We loop through these looking for the String 'name='. When we find this, we read out whatever else makes up this index, which will be the value associated with the name we passed to the function at the beginning.

Erasing an entry is easy — simply recreate a cookie with its expiration date set to -1.