If you’ve done any web development, at all, ever, you’ve undoubtedly used–and cursed–the clunky cookie.

In all fairness, cookies are nice for what they are.  You can store basic information about users and their behaviors on the user’s machine for use on your site, and they are fairly reliable. The problem with them, though, is that they are clunky.  Clunky to set, clunky to expire, and quite limited in terms of storage capability–4000-some characters…lame.

Fortunately, in HTML5, we have a much better option for light-weight client-side storage (like cookies) without the clunky-ness, retarded size limits, and potential “leak” issues.  Actually, we have two 🙂

First, let’s talk about the Storage object to which the two options belong.  According to the proposed spec, the Storage object provides access to set, read, and remove “items” which are basically the key/value pairs that everyone is familiar with.  Unlike cookies, however, the key/value pairs do not have an expiration date associated with them, and are removed either by user action or by the cessation of a session.

Enough talk.  Let’s look at the options.

sessionStorage

sessionStorage is an attribute of the Storage object which represents a storage area for each “origin” [read domain].  In other words, sessionStorage is a place you can store stuff for your domain, like user info, favorite colors…whatever.  The unique thing about the sessionStorage attribute, however, is that its lifetime is finite, limited to the current session of the browser.  So, when the session ends (like closing your browser), anything stored in sessionStorage will be purged.  In other words, don’t use it for anything you need to stay around for any period of time!!

localStorage

This one’s simple.  Remember everything I said about sessionStorage?  It’s exactly the same for localStorage, with one major exception: localStorage does not have a finite lifetime.  As long as the user does not deliberately clear the localStorage, its content will persist indefinitely.

Um, okay.  So how do I use them?

Because sessionStorage and localStorage are so similar, they have precisely the same API.  You can access these attributes quite easily with simple JavaScript, and the exposed methods are ridiculously easy to use.

So to get into some code, let’s look at a simple app that will let us enter movie information, comprised of the following data: title, release year, and awesomeness.

To begin, let’s create a shortcut to our storage attribute (localStorage in this example):

<script type="text/javascript">
       var storage = localStorage;
</script>

Pretty crazy hard, huh?  Now I’ll let you build out the form to handle the input of the movie information, but let’s check out a method to handle saving the movie to our localStorage attribute.

<script type="text/javascript">
      function SaveMovie(el) {
           var frm      =    el.form;
          // setup new object to store our movie details
          var movie     =    new Object();
          // add movie details
          movie.title   =    frm.title.value;
          movie.year    =    frm.year.value;
          movie.awesome =    frm.awesome.checked==true ? true : false;
          // get storage object length to see if there are any existing movies
          var inc = storage.length+1;
          // set a key based on increment
          var key = 'movie_'+inc;
          // set storage item with incremented key in case we want more than one movie
          storage.setItem(key,Ext.encode(movie));
          // add movie to our list
      }   
</script>

The first several lines of this are really just setting up the values that I want to insert into localStorage.  If you look closely, however, you’ll that I’m creating an object to store my movie information.  This is because with localStorage, we have a much larger potential for data storage than we ever did with cookies.  Therefore, I can use JSON-formatted strings if I want to store an object as the “value” of my key/value pair.  This is super nice because I can use a framework (like ExtJS) that handles JSON serialization and deserialization to nicely work with localStorage data as objects, rather than having to rely on clunky string parsing with regex and other nonsense.

Once I have my data object ready, I can invoke the setItem() method of the localStorage attribute to save the movie.  The setItem() method takes two arguments, the name of the key and the value.  Here, I simply passed a dynamically named variable as the key, and my serialized object as the value.

That’s about it.  With setItem(), we can easily add movies to our heart’s content to localStorage.  But how do we get it out?  I’ll show you:

storage.getItem(key);

Pretty simple, right?  And what if you want to remove a move?

storage.removeItem(key);

And what if you want to go nuclear on localStorage?

storage.clear();

Debugging

If you want some awesome debugging of sessionStorage and localStorage, use Chrome.  In the Developer Tools, under “Storage”, you can see any and all key/value pairs that have been saved to either the sessionStorage or localStorage attributes.  Additionally, you can modify and/or remove them in order to nail down exactly the best way to structure your code.  It’s really quite awesome, and I’m looking forward to Firebug hopefully introducing something similar when it’s updated for Firefox 4 and its shiny new tabs.

Wrapping Up

As seen, dealing with the relatively new Storage object and its localStorage and sessionStorage attributes is ridiculously simple.  Once full browser support is provided (it’s pretty wide-spread as it is right now), I think we’ll begin to see a lot of great, slick apps utilize these while the reign of the cookie will begin to dwindle.

If you’d like to check out the full mini-app, see the localStorage demo, as well as the sessionStorage demo.  (Hint: Try closing your browser, and then revisiting after trying each one to see the difference…)

But don’t take my word for it.  Build something of your own, and share your thoughts! 🙂

Advertisements