JavaScript - Cookies




JavaScript - Cookies

Cookies were originally invented by Netscape to give 'memory' to web servers and browsers. The HTTP protocol, which arranges for the transfer of web pages to your browser and browser requests for pages to servers, is state-less, which means that once the server has sent a page to a browser requesting it, it doesn't remember a thing about it. So if you come to the same web page a second, third, hundredth or millionth time, the server once again considers it the very first time you ever came there.

This can be annoying in a number of ways. The server cannot remember if you identified yourself when you want to access protected pages, it cannot remember your user preferences, it cannot remember anything. As soon as personalization was invented, this became a major problem. Cookies were invented to solve this problem. There are other ways to solve it, but cookies are easy to maintain and very versatile.

How cookies work

A cookie is nothing but a small text file that's stored in your browser. It contains some data, A name-value pair containing the actual data, An expiry date after which it is no longer valid, The domain and path of the server it should be sent to.

As soon as you request a page from a server to which a cookie should be sent, the cookie is added to the HTTP header. Server side programs can then read out the information and decide that you have the right to view the page you requested or that you want your links to be yellow on a green background. So every time you visit the site the cookie comes from, information about you is available. This is very nice sometimes, at other times it may somewhat endanger your privacy. Fortunately more and more browsers give you the opportunity to manage your cookies (deleting the one from the big ad site, for example). Cookies can be read by JavaScript too. They're mostly used for storing user preferences.

Cookies are small items of data, each consisting of a name and a value, stored on behalf of a website by visitors’ web browsers. In JavaScript, cookies can be accessed through the document.cookie object, but the interface provided by this object is very primitive. Cookies.js is a JavaScript object that allows cookies to be created, retrieved, and deleted through a simple and intuitive interface.

Creating cookies

Cookies can be created using the set function, which takes the cookie name and value as parameters -

// create a cookie
Cookies.set('theme', 'green');

A cookie set in this way will be deleted when the visitor closes their web browser, will only be accessible within the current directory on the current domain name, and will be sent over both encrypted and unencrypted connections. These features can be controlled through an optional third parameter, which is an object with four possible properties. The expiry property allows the cookie can be given an expiry date. Cookies with an expiry date will persist between browsing sessions, and only be deleted when the expiry date is reached or the visitor instructs the browser to do so. The value of the property can be either a date on which the cookie will expire or a number of seconds after which the cookie should expire -

// create a cookie that expires after one hour
Cookies.set('theme', 'green', {expiry : 3600});

// create a cookie that expires on 1st January 2030
Cookies.set('name', 'Kate Morley', {expiry : new Date(2030, 0, 1)});

Every cookie is accessible only within a particular path, which defaults to the current directory — for example, a cookie set on a page at http://example.com/news/ would by default be accessible from http://example.com/news/archives/ but not from the home page of the site. The path property allows an alternative path to be specified -

// create a cookie that is accessible anywhere on the site
Cookies.set('theme', 'green', {path : '/'});

// create a cookie that is accessible only within the news directory
Cookies.set('country', 'uk', {path : '/news/'});

Every cookie is accessible only on a particular domain, which defaults to the current domain and its subdomains — for example, a cookie set on news.example.com would by default be accessible from archives.news.example.com but not from the main domain example.com. The domain property allows an alternative domain to be specified -

// create a cookie that is accessible on all subdomains of example.com
Cookies.set('theme', 'green', {domain : '.example.com'});

Finally, the secure property can be set to true to instruct the browser to send the cookie only over encrypted connections -

// create a cookie that is sent only over encrypted connections
Cookies.set('theme', 'green', {secure : true});

What is an JavaScript Cookies ?

JavaScript cookies are data files that contain the information provided by users. These files are stored on users' computers. This tutorial explains how cookies are created and used to enhance websites. You will learn how to write them in JavaScript from scratch, going through all of the necessary parameters. This tutorial also covers the ways to modify, update, and delete cookies. Furthermore, you will learn to make JavaScript set cookie.

Create a Cookie with JavaScript

JavaScript can create, read, and delete cookies with the document.cookie property. With JavaScript, a cookie can be created like this -

document.cookie = "username=John Doe";

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed -

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

How to Build Javascript Cookies

Setting a cookie using JavaScript will require some knowledge of how websites work, how websites share and retrieve data, and how to read code in HTML and JavaScript, but this knowledge can be picked up within an hour or so (even if you have little technical knowledge). You simply need to understand the limited amount of code that you will need to read. You will not need to reproduce a cookie by yourself from scratch, as JavaScript cookie templates and instructions on how to set cookies can be found all over the web.

For a detailed breakdown of what the individual snippets of code found in a cookie mean, take a look at SitePoint’s post on the topic. Additionally, HTML Goodies wrote a detailed post about inserting JavaScript cookies into the HTML of your website. Remember that when specifying the relevant domains of your website in your cookie, so that you can capture data, you can specify the entire website, or even just specific webpages. It is up to you. If you want to expand your aptitude with setting cookies, you can even alter the CSS (the style of your website) to make your cookies appear more graphically-friendly and appealing to clients and visitors.

Change a cookie with Javascript

With JavaScript, you can change a cookie the same way as you create it.

document.cookie = "username=John Smith; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

Delete a cookie with Javascript

Deleting a cookie is very simple. Just set the expires parameter to a passed date.

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Note - that you don't have to specify a cookie value when you delete a cookie.

Javascript cookie example

In the example to follow, we will create a cookie that stores the name of a visitor. The first time a visitor arrives to the web page, he will be asked to fill in his name. The name is then stored in a cookie. The next time the visitor arrives at the same page, he will get a welcome message. For the example we will create 3 JavaScript functions. A function to set a cookie value. A function to get a cookie value. A function to check a cookie value

Scripting Cookies

So far, I have explained what cookies are, as well as some of their pros and cons. Now it’s time to see what functions JavaScript exposes to work with them. Unfortunately, the first thing I have to say is that JavaScript doesn’t have native methods to easily work with cookies. JavaScript can create, retrieve, and delete cookies using the document.cookie property, but it’s not really a pleasure to use. Every time you are forced to deal with split(), substring() and for loops. Please note that while you can treat document.cookie like a string variable, it’s actually more than that. For example, take the following script −

Syntax

document.cookie = "visits=3; path=/;";
document.cookie = "last-visit=Mon, 15 Oct 2012 19:36:00 GMT; expires=Wed, 31 Oct 2012 11:00:00 GMT;";

If you then print document.cookie, you’ll get an unexpected result as shown below -

console.log(document.cookie);
// print visits=3; last-visit=Mon, 15 Oct 2012 19:36:00

By now, you’ve seen the hardships of dealing with cookies in JavaScript. So, it’s time to create our own functions to easily manage them. The following function will help you to create a cookie. Please note that the expires parameter can be either an instance of a Date object or a number which indicates the number of days. The latter can be a negative number, which sets the expiration date in the past.

function createCookie(name, value, expires, path, domain) {
  var cookie = name + "=" + escape(value) + ";";

  if (expires) {
    // If it's a date
    if(expires instanceof Date) {
      // If it isn't a valid date
      if (isNaN(expires.getTime()))
       expires = new Date();
    }
    else
      expires = new Date(new Date().getTime() + parseInt(expires) * 1000 * 60 * 60 * 24);

    cookie += "expires=" + expires.toGMTString() + ";";
  }

  if (path)
    cookie += "path=" + path + ";";
  if (domain)
    cookie += "domain=" + domain + ";";

  document.cookie = cookie;
}

You can call this function as shown below.

createCookie("website", "audero.it", new Date(new Date().getTime() + 10000));
createCookie("author", "aurelio", 30);

Now that you set a cookie, you need to be able to retrieve them. You’ll do it using a given key and the following getCookie() function. It returns the value of the key if it’s found, and null otherwise.

function getCookie(name) {
  var regexp = new RegExp("(?:^" + name + "|;\s*"+ name + ")=(.*?)(?:;|$)", "g");
  var result = regexp.exec(document.cookie);
  return (result === null) ? null : result[1];
}

Using getCookie() is very simple. You simply pass the key as a parameter like as shown below.

console.log(getCookie("author")); // print aurelio
console.log(getCookie("nothing")); // print null

Now we need the last function to delete a cookie. The function shown is very simple because it relies on getCookie() to test if the given name is set, and createCookie() to set the expiration date in the past.

function deleteCookie(name, path, domain) {
  // If the cookie exists
  if (getCookie(name))
    createCookie(name, "", -1, path, domain);
}

Given that function, to delete a cookie you can simply write -

deleteCookie("author");
console.log(getCookie("author")); // now print null

Using the functions shown, you’ll be able to easily manage cookies. The web is also full of plenty of other cookie handling functions. Of the plethora of functions you can find, I’d like to show the ones written by Peter-Paul Koch (P.P.K.), a guru of front-end development, on quirksmode.com. I’d like to thank him for allowing me to include them in this article. P.P.K’s function to create a cookie is shown below.

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=/";
}

Similarly, to retrieve a cookie, use the following function.

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

And this is the function to delete a cookie.

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