Ioannis Panagopoulos blog

Tutorials on HTML5, Javascript, WinRT and .NET

HTML5 Client Storage. An introduction on the new cookies.

by Ioannis Panagopoulos

Let’s talk about cookies. In fact let’s revisit cookies and see how we use them and what nightmares they bring along. Cookies are all about client storage. They are all about storing persistent information at client side.

The syntax for creating/reading them is as follows. Imagine that we want to store client side the value 17 in a cookie named id. This is done by the following Javascript: document.cookie=”id=17;expires=Mon,6 Feb 2012 12:00:00”;

When we later want to read the value of the cookie named id we need to search within document.cookie for the string “id=” and fetch the value up to the next “;” character.

Based on the previous definitions we may come up with three nice Javascript functions that make our lives a littler easier:

 

Creating a cookie

function SetCookie(name, value, expirationInDays) {
    var now = new Date();
    var expire = new Date();
    var newCookie = name + "=" + value;
    if (expirationInDays != null && expirationInDays != 0) {
        expire.setTime(now.getTime() + 3600000 * 24 * expirationInDays);
        newCookie += ";expires=" + expire.toGMTString();
    }
    document.cookie = newCookie;
}

Reading the value of a cookie

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

Or of course you can use a JQuery plugin which provides an implementation for the basic operations with cookies.

Now some basic facts:

 

  • To update a cookie you just create the same cookie with the updated value.
  • If you do not define an expiration date then the cookie will expire as soon as the browser’s window is closed. This cookie is also called a session-based cookie.
  • if you want to delete a cookie then you must call SetCookie for the cookie without providing an expiration date and by setting its value to blank. As a consequence the cookie will be removed when the browser’s window is closed (so it is actually an inferred delete!)
  • Cookies persist among tabs in a browser. So storing tab critical information in the cookie may result in unwanted behavior.

 

So we need a better and easier way to create/update/delete values that we store client-side, and easier way to handle expiration (values that persist even when the browser is closed or values that they don’t). And that is exactly what HTML5 offers us through the use of the following:

 

  • sessionStorage: Equivalent to session-based cookies. Is erased when the browser window is closed but also the values are not shared among browser’s tabs.
  • localStorage: Equivalent to cookies with expiration date but does not expire.

 

The API is native to Javascript and is as follows (for the same example with the value 17 called id). For sessionStorage just replace localStorage with sessionStorage:

 

  • Create: localStorage.setItem("id",17);
  • Read: localStorage.getItem(“id”);
  • Remove: localStorage.removeItem(“id”);
  • Clear all:localStorage.clear();

 

Finally don’t forget that like cookies in those values you can even store full Javascript objects as follows where we store the object Client in sessionStorage using JSON.stringify and retrieve it with :

var Client = {
    firstName:"John",
    lastName:"Panagopoulos",
    coolFactor:10
}
function storeClient() {
    sessionStorage.setItem("client", JSON.stringify(Client));
}
function getClient() {
    var retrievedClient = JSON.parse(sessionStorage.getItem("client"));
    console.dir(retrievedClient);
}

Well this is it. Of course there are some other sophisticated methods to store stuff client-side the “HTML5” way such as Web SQL Databases or the cache but we will cover those in a future post.

Shout it

blog comments powered by Disqus
hire me