HTML5 Web Storage Example

In this example, I will present you how to use HTML5 storage.

We will see the two storage types introduced in HTML 5 : localStorage and sessionStorage.

As a working example we will create a Todo List, first without any storage and then we will add some storage.

The Storage API

The HTML Storage Api allows you to store some values in the user browser, in a more "fashion” and secure way than cookies.

The data is stored as key/value pairs.

The Storage Api add two properties to the Window objet : Window.sessionStorage and Window.localStorage.

It also add an event : the StorageEvent, this event will be fired when a storage area changes.

Methods and Properties

Both localStorage and sessionStorage use the same methods and properties :

  • length : This property return the number items stored in the Storage object.
  • key(n) : This will return the data stored at the index n in the storage object.
  • getItem(name) : This will return the data stored in the storage object and whick key is name.
  • setItem(key, value) : This will store the value, for the key in the storage, or update the value, if the key already exists.
  • removeItem(name) : This will remove the data identified by the key name in the storage.
  • clear() : This will empty all keys of the storage.

Limitations

The main limitation known about the storage elements is the size of the data you can store in the storage.

The limitation is not specified in the Storage Api Specification, so it’s a browser limitation.

Most of them limit the size at 5 MB.

You can find more information about your browser (and test it), on this site.

Detecting Browser Capability

As the Storage API is a feature of modern browser you should have a way to detect if the user browser support Web Storage.

We should only, use the following code to detect the presence of either localStorage or sessionStorage in the window Object :

function supports_html5_storage(){
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch(e) {
        return false;
    }
}

This code suppose that if a browser support localStorage it will also support sessionStorage.

Source from Dive Into HTML5.

Let see an example…

Setting up the Example

As I said in the introduction, we will create a Todo List application. The application will allow us to add a task, mark a task as done, remove a task, edit a task and clear the list.

HTML

First create the necessary HTML :

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Todo List</title>
</head>
<body>
    <form id="taskform">
        <input type="text" id="task" /><input type="submit" value="Add">
    </form>
    <ul id="tasks"></ul>
    <button id="clear">Clear</button>
</body>
</html>

The document contains a form, with a text element, for writing the task description, and a button to submit the form.

As we will not have server side code, we do not need to define the method and action attributes for the form element.

Then the document will contain a list of tasks as an unordered list.

Each task will be identified as a list item element (li) like this :

<li>
    <span>Some Thing to do ...</span>
    <a href="#">delete</a>
</li>

And, at the end of the document we added a "Clear” button to allow the user to clear the whole list.

CSS

I won’t design the application, as it is not the main purpose of the document.

The only CSS code I will use is, the style that will add a line through the "done” task.

ul li.selected span{
    text-decoration: line-through;
}

This CSS code will affect only the span element, but not the link.

No Storage

First we will create the application without any storage support.

Adding a task

The task will be added when the form is submitted :

// Catch the form submission
document.getElementById('taskform').addEventListener('submit', function(e){

    // prevent the browser to reload the page
    e.preventDefault();

    // get the task element value
    var value  = document.getElementById('task').value

    // add the to the list
    addTask(value);

    // reset the task element value
    document.getElementById('task').value = '';

}, false);

As you can see, we delegate the creation of the task in the document to the `addTask function.

Here is the function :

// Create the task element in the dom
function addTask(value){
    // get the um element
    var ul = document.getElementById('tasks');

    // create the needed node elements
    var li = document.createElement('li');
    var a = document.createElement('a');
    var span = document.createElement('span');

    // Create the "delete" link
    a.setAttribute('href', '#');
    a.textContent = 'delete';

    // Add the Task text to the Span element
    span.textContent = value;

    // Add the elements in the list item
    li.appendChild(span);
    li.appendChild(document.createTextNode(" - "));
    li.appendChild(a);

    // Append the tak to the Dom
    ul.appendChild(li);

    // Catch the click on the task text to mark it done
    a.addEventListener('click', function(e){
        var span = e.target;
        span.parentNode.remove();
    }, false);

    // Catch the click on the delete link to remove the task
    span.addEventListener('click', function(e){
        var span = e.target;
        span.parentNode.classList.toggle('selected');
    }, false);
}

And now, we need to manage the click on the "clear” button :

document.getElementById('clear').addEventListener('click', function(e){
    document.getElementById('tasks').innerHTML = '';
}, false);

The application is now working ! if you reload the page the task list will be empty, so let see

  • how to use the Storage
  • to save the data during the user session …

sessionStorage

In order tp keep the tasks during the user session, we will store the tasks in the `sessionStorage.

Edit the addTask function So we have to edit the addTask function by adding the following code :

// store to storage
if( supports_html5_storage() ){
    // retreive the existing tasks
    var storage = sessionStorage.getItem("tasks");

    // setting the datas array (if storage is empty)
    var datas = [];

    // if there is some tasks in the storage
    if( storage !== null){
        // We Parse the Storage Value
        datas = JSON.parse(storage);
    }

    // Now we push task to the Data
    datas.push(value);

    // And then we store the "stringified" datas in the sessionStorage.
    sessionStorage.setItem('tasks', JSON.stringify(datas));
}

This code will store tasks as "stringified” array in the `sessionStorage.

❗️ We have to stringify objects and arrays before we can add them to the storage.

remove from storage

Here is the new code for removing the task from the list AND the sessionStorage :

// Catch the click on the task text to mark it done
a.addEventListener('click', function(e){
    var span = e.target;
    span.parentNode.remove();

    if( supports_html5_storage() ){
        var datas = [];
        var tasks = document.getElementById('tasks');

        // we recreate the datas array from the Dom ...
        for(var I =0; I < tasks.childNodes.length; i++){
            if( tasks.childNodes[i].tagName === 'LI'){
                datas.push(tasks.childNodes[i].childNodes[0].innerHTML);
            }
        }

        // We save the tasks
        sessionStorage.setItem('tasks', JSON.stringify(datas));
    }
}, false);

This code will remove the task from the dom, recreate the datas array from the dom list, then save the datas in the sessionStorage.

Clear the list and the storage

Here is the new code when user click on the clear button :

document.getElementById('clear').addEventListener('click', function(e){
    document.getElementById('tasks').innerHTML = '';

    if( supports_html5_storage() ){
        sessionStorage.removeItem('tasks');
    }

}, false);

We simply remove the “tasks” key from the storage.

Load the existing storage

Now, if the storage is not empty, we have to load data and add to the list …

// load from storage
if( supports_html5_storage() ){
    var storage = sessionStorage.getItem("tasks");
    var datas = [];
    if( storage !== null){
        datas = JSON.parse(storage);
        for(var I = 0; I < datas.length; i++){
            addTask(datas[i], true);
        }
    }
}

As you should noticed it, I added a parameter to the addTask function call. Without this parameter every call will add the element again in the sessionStorage.

function addTask(value, loading) {
    // Existing Code
    ...
    // store to storage
    if( supports_html5_storage() && loading ){

Now if you reload the page the task list is kept in the sessionStorage, but if you close the browser, and navigate to the page, all the data is not accessible anymore.

localStorage

Let see how to use localStorage to store the tasks even if the browser is closed …

You only have to replace all the sessionStorage string with localStorage, like this :

// store to storage
if( supports_html5_storage() ){
    // retreive the existing tasks
    var storage = localStorage.getItem("tasks");

    // setting the datas array (if storage is empty)
    var datas = [];

    // if there is some tasks in the storage
    if( storage !== null){
        // We Parse the Storage Value
        datas = JSON.parse(storage);
    }

    // Now we push task to the Data
    datas.push(value);

    // And then we store the "stringified" datas in the Storage.
    localStorage.setItem('tasks', JSON.stringify(datas));
}

All the code is in the source zip (see download sectio below).

Events

The Storage Api add a new event on the window object, so you can execute some code when even local or session storage is manipulated.

window.addEventListener('storage', function(e){
    // Log all event ...
    console.log(e);
}, false);

Here are the properties of the storage event :

  • key : Represents the key changed. Null if the change is caused by the storage clear() method
  • newValue : The new value of the key. Null if the change has been invoked by storage clear() method or the key has been removed from the storage.
  • oldValue : The original value of the key. Null if the change has been invoked by storage clear() method or the key has been newly added and therefor doesn’t have any previous value.
  • storageArea : Represents the Storage object (local or session) that was affected.
  • url : It represents the address of the document whose key changed.

❗️ NOTE : “Storage event handlers only fire if the storage event is triggered from another window.” from : http://stackoverflow.com/questions/3055013/html5-js-storage-event-handler.

Download

You can dowload the full example here : HTML5 Web Storage Example