One of my favorite features of the ‘new’ HTML5 spec is the use of local storage. Local storage is a persistent store in the user’s browser that can save key/value pairs without much overhead. This data is never transferred to the server, it only ever exists locally (hence the name), and can be used for any sort of data storage. There is an upper limit on the amount of data that you can store, and that is dependent on the browser.

Why would I want to use local storage?

As I mentioned before you can use it for any data storage. So there aren’t any real limitations on what you can store. However everything is stored in plain text, and is stored in the browser so you wouldn’t want to put sensitive information in there.

I tend to use local storage for static data that I know that I am going to use over and over again throughout an application, such as look up data. Local storage is very useful when creating single page applications (SPAs) because you can load the data into local storage and never have to go back to the server to grab it. And if this is a site that your users are going to be on a lot they won’t have to go back to the server the next time around to get it since the data is already stored in their browser.

Just a quick word about private browsing. You can still use local storage when in private browsing. However that data is only persistent during the private browsing session. If you stored things in local storage before going into private browsing those will not be available during the private session. Most applications won’t have to worry about this, just something interesting to note.

Usage

In the example below I am going to be using JQuery and a tool called Modernizr in order to make testing for local storage a little bit easier. Modernizr is a JavaScript file that will allow you to test for many different HTML5 and CSS3 features before you try to use them to allow you to fail gracefully. I highly recommend you check it out.

So let’s look at some code

function addLocalStorage(key, value) {
   if (Modernizr.localstorage) {
      localStorage[key] = value;
   }
   else {
      alert("No localstorage");
   }
}

This small function takes in two variables, and adds the value to local storage. As you can see there isn’t a whole lot here. And that is, one reason, why local storage is so nice, because it is so simple to use. As you can see in my if-statement I am testing to see that local storage exists before I try to use it. In actual production code I would have a fail-over to provide the same functionality in either case.

If I already know what I want my key to be I can also implicitly add the property to the localstorage variable. In the example below I am storing an array of different states into a variable named States in local storage.

 localstorage.States = [ 'Active, Inactive, Pending' ];

So where does this actually live. This is a screen shot from Chrome’s developer tools that shows what my local storage looks like
local storage in browser
You can see I have a Key/Value pair for Hello world, and an entry for my different states.

Now that we put things into local storage how do we get it out?

 function readLocalStorage(key) {
    if (Modernizr.localstorage) {
       return localStorage[key];
    }
    else { alert("No LocalStorage"); }
 }

Again, not a whole lot here. Just use the key to get things back out. You can also use the implicitly typed example (localstorage.States).

Summary

  • You can use local storage to quickly and easily store data in the user’s browser
  • Storage is persisted even after browser is closed.
  • Don’t store any sensitive information as everything is stored in plain text.
  • Don’t store volatile data so you don’t have to keep swapping out the information stored there.

This post is also posted over on my company’s blog. Go

Full Code listing

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="scripts/jquery-1.9.0.js"></script>
        <script src="scripts/modernizr-2.6.2.js"></script>
 
 
        <script>
 
            $(document).ready(function () {
 
                $("#btnSave").click(function () {
 
                    var key = $("#txtKey").val();
                    var value = $("#txtValue").val();
 
                    addLocalStorage(key, value);
                    alert("Saved");
                    
                    $("#txtKey").val();
                    $("#txtValue").val();
 
                });
 
                $("#btnGetValue").click(function () {
                    var key = $("#txtKeyForRetrieve").val();
 
                    var value = readLocalStorage(key);
 
                    $("#storageValue").text(value);
 
                });
 
                function addLocalStorage(key, value) {
                    if (Modernizr.localstorage) {
                        localStorage[key] = value;
                    }
                    else {
                        alert("No localstorage");
                    }
                }
 
                function readLocalStorage(key) {
                    if (Modernizr.localstorage) {
                        return localStorage[key];
                    }
                    else { alert("No LocalStorage"); }
                }
            });
 
        </script>
    </head>
    <body>
 
        <section>
            <h2>Save to LocalStorage</h2>
            <p> Key: <br/>
                <input id="txtKey" type="text"/>
            </p>
            <p>
                Value: <br/>
                <input id="txtValue" type="text"/>
            </p>
            <br/>
            <input type="submit" value="Save" id="btnSave"/>
        </section>
 
        <section>
            <h2>Retrieve Localstorage</h2>
            <p> Key: <br/>
                <input id="txtKeyForRetrieve" type="text"/>
            </p>
 
            <div id="storageValue"></div>
                
            <input type="submit" value="Retrieve" id="btnGetValue"/>
        </section>
    </body>
</html>