localstorage provides a way to persist data on the client side without using cookies. The localStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user’s mailbox, on the client for performance reasons.
This code uses both Modernizr and jQuery—Modernizr to let us know whether we need to support cookies instead of local storage and jQuery to insert HTML into the DOM to show that our local storage worked.
In the last post in this series, we showed how you can Get Started with Modernizr and Get Started with JQuery.
You can use Modernizr to detect is localStorage is available, and if not you can fall back to good old cookie storage.
And in our HTML:
IE8 and IE9 running in IE7 mode will support
localstorage. From a user standpoint, this is probably what you want for your users. But you will want to turn off
localstorage while you are testing. Open “Internet Options” for IE, go to the “Advanced” tab, and clear “Enable DOM storage” to turn off
localstorage and thus test our code.
So we use some code to save something to local storage.
Code for localstorage
First, I’ll add some HTML with an input box whose data I’ll store.
After my code loads Modernizr, I can check to see if local storage is supported. If so, I can then use local storage or use a cookie.
I can save the data in local storage using a key, value pair using setItem(). I can then retrieve the value by using getItem().
For the purposes of demonstration, I use jQuery to insert value that I retrieve from local storage.
The code $(“#yoursavedname”).append() method adds the text passed as the parameter into the yoursavedname div.
And if local storage is not available, I just use a cookie.
Local Storage Methods
The following properties and methods are supported by both session and local storage objects.
- clear. Removes all key/value pairs from the Web Storage area.
- getItem. Retrieves the current value associated with the Web Storage key.
- key. Retrieves the key at the specified index in the collection.
- length. Retrieves the length of the key/value list.
- remainingSpace. Retrieves the remaining memory space, in bytes, for the storage object.
- removeItem. Deletes a key/value pair from the Web Storage collection.
- setItem. Sets a key/value pair.
For More Information
- Caching in on HTML5 Local Storage in Visual Studio Magazine
- Introduction to Web Storage on MSDN
- Learn how to use Modernizr from the ASP.NET MVC3 Tools Update to store user data via HTML5 localStorage
- Introducing the HTML5 storage APIs from Adobe
- Web Storage specification
Sample code is available in the DevDays GitHub repository. See https://github.com/devdays/html5-tutorials