Taking a Dive into HTML5 – Web Storage

HTML5 is getting a lot of attention these days – especially when it comes to video. This tutorial is going to cover a feature added to HTML5 that I don’t think is getting enough attention – web storage.

Prior to web storage, most websites used cookies to store information on the client’s computer. Cookies, for the most part, work great for simple storage. They do, however, have one major drawback. If the user is visiting your site on two separate windows or tabs, information stored in cookies will be shared between them. To handle this case, the web storage in HTML5 has been split into two pieces: localStorage and sessionStorage. The first one works like cookies, saving information for an entire site (origin). The second one, sessionStorage, will store information for each origin but keep it isolated between windows or tabs.

Before we get started, I should note that not every browser supports web storage. Wikipedia is maintaining a pretty good list of HTML5 browser compatibility that should probably be consulted before using storage in a production environment.

Reading and Writing Values

Both mechanism use the same object as defined in the web storage spec, Storage. Let’s take a look at this interface.

interface Storage {
  readonly attribute unsigned long length;
  getter DOMString key(in unsigned long index);
  getter any getItem(in DOMString key);
  setter creator void setItem(in DOMString key, in any data);
  deleter void removeItem(in DOMString key);
  void clear();
};

Hats off the creators of this, as I don’t think there could have been a simpler interface for storing values. At its core, this is basically a dictionary mapping string keys to object values. For the most part, pretty much anything can be stored in here – as long as it can be cloned using the structured clone algorithm

Let’s take a look at how do use this, first using localStorage.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   <head>
      <title></title>
      <script type="text/javascript">
         function load()
         {
          var value = localStorage.getItem("myKey");
         
          if(!value)
          {
            alert("No item found, adding to localStorage");
            localStorage.setItem("myKey", "myValue");
          }
          else
          {
            alert("Item found: " + value);
          }
         }
      </script>
   </head>
   <body onload="load()">
       
   </body>
</html>

In this example, if the value hasn’t been stored yet, you’ll receive this alert:

No item alert

The next time the page is loaded, you’ll now receive this alert:

Item found alert

As you can see, using localStorage is incredibly easy. This value will now be stored indefinitely on the client’s computer ready for me to retrieve whenever they visit my website again.

Using sessionStorage is just as easy. All we have to do is replace the object we’re using and we’re done.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   <head>
      <title></title>
      <script type="text/javascript">
         function load()
         {
          var value = sessionStorage.getItem("myKey");
         
          if(!value)
          {
            alert("No item found, adding to sessionStorage");
            sessionStorage.setItem("myKey", "myValue");
          }
          else
          {
            alert("Item found: " + value);
          }
         }
      </script>
   </head>
   <body onload="load()">
       
   </body>
</html>

The code is nearly identical to the previous code, however this time, if you open the site in two different tabs, you’ll receive the “No item found” message for each tab. In the previous example, the value existed for every new tab or window created.

One thing to remember when dealing with HTML5 web storage is that it does not cross browsers. The spec does not outline where or how a browser must store the data. Therefore if the user visits your site in one browser one day, then in a different browser the next, you will not be able to see values that were stored by the other browser.

Listening for Changes

The HTML5 spec outlines an event that client’s can attach to in order to receive updates whenever a storage (local or session) changes. At this point in time, however, I wasn’t able to get it working in Chrome (6.0.401.1 dev). I was, however, able to get the following code working in Opera.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
   <head>
      <title></title>
      <script type="text/javascript">
         function load()
         {
         localStorage.clear();
          var value = localStorage.setItem("myKey", "myNewValue");
          alert(localStorage.getItem("myKey"));
         }
         
         function storageChanged(e)
         {
          alert("Storage changed.");
         }
      </script>
   </head>
   <body onstorage="storageChanged()" onload="load()" >
       
   </body>
</html>

In Opera, the storageChanged event will fire twice – once for when the localStorage is cleared, and again when the value is set.

Although we’re moving in the right direction, HTML5 still has a ways to go before it’s fully adopted. Web Storage has a great amount of potential in the future of web apps and I can wait to see what developers are able to do with it.

Leave a Reply

Your email address will not be published. Required fields are marked *