Tutorial HTML5 Local Storage

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

We will learn about HTML5 local storage in this tutorial.  Local storage is newer technology that can used instead of cookies for storing web app data in user’s browser.  But unlike cookies, its data is not sent back to the server on each request.

Data from 2MB to 10MB is stored on local computer and is browser and machine specific.  “local storage” persist across sessions and machine restarts.  “session storage” only persists during that browsing session.  Depending on the browser, local storage will not work or not persist across sessions if incognito or private mode is used.

Data is stored in key value pairs and always as strings.  But you can use  parseInt(), JSON.parse() and JSON.stringify() to convert.

Let’s create a webpage that asks for user name and store that in local storage. …

ask-name

The next time you return even after you close your browser or shut down your machine, it will know your name and display your name.  We start with the following HTML

check-localstorage-support

Setting Local Storage

The script at the bottom detects if local storage is supported by using the function localStorageSupported() from the Sitepoint article “An Overview of the web storage API“.

Now when button is clicked, we get the value of the input box and store that value to local storage under the key of “username”…

save to local storage

We wrapped it in a try catch block in case something goes wrong such as exceeding quota, etc.

Note that the following are also equivalent statement for saving to local storage…

localStorage[“username”] = userName;
localStorage.usernames= userName;

Viewing Local Storage

To see your local storage values in Chrome, click the Resources tab in developer tools …

view-local-storage

Make sure you click the “refresh icon” at the bottom to see the newly updated values.  This is also where you can edit the values or delete them.

The local storage can also be deleted when the user clear browser data.

Reading Local Storage

Now the next step is to get our script to read the “username” value…

read-from-localstorage

The localStorage also has a length property so that you can use it to iterate through all key value pairs…

iterate-localstorage

When you put the web page up on the server, the local storage in developer tool will look different.  It will show the domain name like this …

domain name in local storage

Deleting Local Storage

To delete local storage programmatically, you can do …

localStorage.removeItem(“username”);

or equivalently …

delete localStorage.username;
delete localStorage["username"];

The following will clear all local storage variables on your domain …

localStorage.clear();

sessionStorage

The API for sessionStorage are identical except use “sessionStorage” instead of “localStorage”.