Understanding Web Storage in HTML 5 Part I

Facebook Twitter Google Digg Reddit LinkedIn Pinterest StumbleUpon Email
Download Source

In the blog post we will be looking at another interesting feature of HTML5, which is a Web Storage. This feature allows our web applications to store data onto client's browsers. Prior to HTML5 we have used cookies to store such information on client's machine.

The problem with cookies is that you have a very limited space to store all your important data and the data you store in cookies will be always passed back and forth as part of request and response of your pages. This definitely slows down your pages in case you store lot of information in the cookies. Also it is not very secure since your data is exposed during the request and response.

The HTML5 Web Storage feature is trying to address the exact same issue with the introduction to two new APIs for storing data on clients' machines. These two APIs are,

  • localStorage - Stores data across user sessions until user clears his history and deletes data explicitly
  • sessionStorage - Stores data for only that particular session of the user. As soon as the browser is closed the data will be destroyed.

Benefits of using these new Web Storage APIs

  • Data you store using these APIs are not being send back and forth as part of request/response.
  • You can store a lot more information in these storage as compare to what you were able to store into cookies.
  • Storing and retrieving your data from these storage is much more simpler.

So without any further discussion, let's dive into creating a sample. Again for the demonstration of this sample I will be using Visual Studio 2012. You do not have to use this tool at all if you don't want to since we are not planning to use any Server side technologies here.

In my previous post on HTML5 Geolocation, we created an empty Asp .Net web applications. For this sample we will be working with the same sample.

Creating the Application/Page

Let's start by adding a new HTML page in our existing solution. In case you do not have that project, you can download the one that is attached with this blog post. Let's name our page as localstorage.html. Go ahead and add following JavaScript function. The function basically checks if the localStorage is supported or not.

localStorage Check JavaScript

Go ahead and run the application. Based on the browser you are using you should see appropriate message saying localStorage is either supported or not. I am using Google Chrome for testing and it sure supports localStorage.

localStorage on Chrome

Setting up the Ground

Now, that we know that localStorage is supported, let's go ahead and set up some ground work. I will add two labels and input elements. One of them will accept the key for and the other one will accept the value for the key. That's right, Web Storage is storing values in the form of key-value pairs.

Along with these controls, I will add a reference of jQuery in order to easily access values of these elements and in general making our JavaScript bit simpler and easier to read.

Groundwork Elements

Input Form UI

Next, we will write our JavaScript function that takes values from these boxes and adds them to localStorage. There are 6 main functions provided as part of localStorage API.

  • setItem(key,value)
  • getItem(key)
  • removeItem(key)
  • clear()
  • length()
  • key(i)

The following function wraps the setItem function call, and it expects a key and a value. We will invoke this function on our add button's click event.

 
function AddToLocalStorage() {
    if (window.localStorage) {
        var key = $('#keyBox').val();
        var value = $('#valueBox').val();
        localStorage.setItem(key, value);
    }
}

Button Click wireup

Let's go ahead and run the page and put some values into your input boxes and click the button. Try running the page in Google chrome. Open developer tool bar for your browser by clicking F12 key on your keyboard and expand the localStorage section in the Resources tab.

Button Click wireup

You can see the values you just entered into the input boxes stored in localStorage. Now this is not the most convenient way of looking at our localStorage values. Let's write a small JavaScript function to write down all the key-value pairs from localStorage to an ul element on our page. Let's add the new ul as below.

New Unordered List

 
function ShowLocalStorage() {           
    $('#storageData').empty();
    for (var i = 0; i < window.localStorage.length; i++) {
        var key = window.localStorage.key(i);
        var val = window.localStorage.getItem(key);
        $('#storageData').append('
  • '+ key + ' - ' + val +'
  • '); } }

    Go ahead and view the page again. I am calling this function after every call of AddItem ,so the ul will be updated with the new item every time. I tried bunch of entries and my page shows up as below.

    Localstorage entries

    In the next blog post we will continue looking at the rest of the functions and see how we can leverage localStorage into our applications.