Click here to Skip to main content
15,887,822 members
Articles / Programming Languages / C++

Using Web Storage in Web Applications

Rate me:
Please Sign up or sign in to vote.
4.71/5 (4 votes)
24 Feb 2012CPOL4 min read 25.7K   17   1
Using Web Storage in Web Applications

Web Storage is a specification that was a part of HTML5 but was moved to its own specification. Currently, it is only a W3C editor draft but it is implemented in all the major browsers (even in IE from IE8) by the name Local Storage or DOM Storage. In this post, I'm going to explain what is Web Storage and how you can use it even today in your web application/site.

Before Web Storage Came to the World

The need to save data and state in web applications/sites is very desirable since they work in a stateless manner. In the early days, we could use cookies in order to save our data but this mechanism was very limited. The cookies had lots of limitations and downsides such as being sent in every HTTP request, 4KB of storage, can be disabled by the users and more. A need for a better mechanism was raised and Web Storage specification was born.

What is Web Storage?

Web Storage is a key/value dictionary that is stored in the web browser and persists your data even if you close the browser/browser tab (resembles the cookie mechanism). Unlike cookies, Web Storage’s data is local to the web browser and isn't sent to the server (no downgrade in traffic performance). In the specifications, there is no limit to the amount of disk space that Web Storage can have but it is said that the browsers need to limit that amount. Web Storage is divided into two different storage objects:

  • sessionStorage – Data in this storage is accessible to any page from the same site opened in that window
  • localStorage – Data in this storage spans multiple windows and lasts beyond the current session

Each web application/site has its own dedicated storage.

Web Storage API

The Web Storage API include the following methods:

  • length – Get the number of key/value pairs in the storage
  • key(n) – Returns the nth key in the storage
  • getItem(key) – Returns the value of the provided key. If the item doesn't exist, it will return null. Pay attention that the returned item is a string! so if you saved data such as integer or boolean, you will have to parse it.
  • setItem(key, value) – Inserts a new value into the storage with the provided key
  • removeItem(key) – Removes the item that is connected to the provided key. If the key doesn't exist, the method does nothing.
  • clear – Empty the storage from its data

For example, here is how you can get or set an item in the localStorage:

C++
localStorage.setItem("key", "value);
var val = localStorage.getItem("key");

You can also use the storage without the get and set methods. You can do that by using the storage as a class with properties that you can access. The previous example can also be used as follows:

C++
localStorage.key = "value";
var val = localStorage.key;

In some browsers, the storage can also be treated as a dictionary (or JavaScript array) with an indexer such as you can see in this example:

C++
localStorage["key"] = "value";
var val = localStorage["key"];

Currently, the indexer behavior isn't part of the specification (but maybe it will be added).
Another aspect of the Web Storage is the storage event that is fired when a change occurs in the storage. That event is wired to the window object and is fired whenever setItem, removeItem or clear are being used. You can wire to that event with a function that receives an event parameter:

C++
if (window.addEventListener) {
    window.addEventListener("storage", handleStorageEvent, false);
} else {
    // for IE versions below IE9
    window.attachEvent("onstorage", handleStorageEvent);
};

function handleStorageEvent(eventData) {
    // Do something
}

The eventData parameter in the previous example will hold the following members for your own use:

  • key – The key that is being changed
  • oldValue – The old value of the key that is being changed
  • newValue – The new value of the key that is being changed
  • url – The address of the document whose key is being changed
  • storageArea – The storage that is being affected by the change

An Example of Use

In the following example, I’m using the localStorage in order to save the number of page load events and to present them to the user:

HTML
<!DOCTYPE html>
<html>
  <head>
  <title>Web Storage Example</title>
  <script type="text/javascript">
  function pageLoadCounter() {
    if (!localStorage.getItem('loadCounter')) {
      localStorage.setItem('loadCounter', 0);
    }

    localStorage.setItem('loadCounter', parseInt(localStorage.getItem('loadCounter')) + 1);
    document.getElementById('counter').innerHTML = localStorage.getItem('loadCounter');
  }
  </script>
</head>
<body onload="pageLoadCounter()">
  <form id="form1">
  <p>
    You have viewed this page <span id="counter"></span> times.
  </p>
  <p>
    <input type="button" onclick="localStorage.clear();" value="Clear Storage" />
  </p>
  </form>
</body>
</html>

This is a very simple example but it shows the use of the API methods like getItem, setItem and clear. As you can see, the data is saved in a string manner so you’ll have to parse it in order to retrieve it. In the example, I parse the counter number which is an integer using the parseInt method. When you will close the browser or tab and then open it again, you will notice that the storage will persist the last counter.

Summary

Web Storage is a new specification that tries to target the lack of opportunities to store client side data. There are other ways to store data on the client such as cookies or using Google Gears with its embedded database which is based on SQLite. I hope that this introduction will help you to get started with a feature that you can use even today. For further information, you can go to Web Storage specification on W3C site.

This article was originally posted at http://feeds.feedburner.com/GilFinkBlog

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
GeneralMy vote of 5 Pin
Pablo Aliskevicius17-Jan-11 20:31
Pablo Aliskevicius17-Jan-11 20:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.