Last Updated: February 25, 2016
·
5.112K
· teddy

HTML5 Web Storage

Web Storage, introduced in HTML5, allows for storage of up to 10MB on the client's computer. This storage is based on key value pairs, keys and values are both stored as strings. For example, parseInt() would be required to retrieve an integer.

There are three different flavors of Web Storage, sessionStorage, globalStorage, and localStorage.

sessionStorage: retains key-value pairs for the lifetime of a single tab.

globalStorage: now deprecated, do not use it, use localStorage instead.

localStorage: persists beyond the current session.

Of course, to start check to see if storage is available in the client window

function supportsLocalStorage()
{
    try
    {
        //local storage is an alias for window['localStorage']
        return ('localStorage' in window && window['localStorage'] !== null);
    }
    catch (e) { console.log(e.stack); }
    return false;
}

The two current Web Storage objects, sessionStorage and localStorage, each have the same methods and properties. The most useful are:

-setItem: a method assigns a value to a key, if the key already exists, it will update the value.

function addData(key, data)
{
    //add data to new key, or replace value if the key already exists with new data
    try
    {
        //error isn't thrown in MSIE
        if (browser == "MSIE")
        {
            if (getRemainingSpace() - data.length < 0)
                return false;
        }

        //add the value to the key, equivalent to localStorage.setItem('key', 'value')
        localStorage[key] = data;
        return true;
    }
    catch (e)
    {
        console.log(e.stack);

        if (e.message == 'An attempt was made to add something to storage that exceeded the quota.')
        {
            //handle error, there is too much data
            console.log('too much data');
        }

        return false;
    }
}

-getItem: a method retrieves a key from storage, if the value does not exist, returns undefined.

function getData(key)
{
    //attempt to get the value from key value pair
    var data = localStorage[key];

    if (typeof data !== 'undefined')
    {
        //data exists
        console.log('localStorage[' + key + '] = ' + data); 
    }
    else
    {
        //cache returned null, image was not in the cache   
        console.log(key + ' is not a key contained within the local storage dictionary');
    }
}

-removeItem: a method to remove a key-value pair

function removeData(key)
{
    //remove data at a single key
    localStorage.removeItem(key);   
}

-clear: a method to remove all key-value pairs from storage

function clearData()
{
    //clear all data
    localStorage.clear();   
}

-length: a property corresponding to the number of elements in storage.

function getLength()
{
    //return the number of items in local storage
    return localStorage.length;
}

-remainingSpace: a property, that only exists within IE, corresponding to the space that remains in the cache, in Bytes. To achieve the same thing in browsers that are not MSIE, utilize the JSON.stringify method. The available storage space is not consistent among browsers, see Web Storage Support Test for each browser's cache size restrictions.

function getRemainingSpace()
{
    //return the number of bytes still available in localStorage
    if (browser == "MSIE")
        //only IE supports this function
        return localStorage.remainingSpace; 
    else
        //use info from Web Storage Support Test to get available bytes based on browser
        return available_bytes - JSON.stringify(localStorage).length;   
}

*note: Web Storage will not work in IE for file:// protocol.

Further reading:

Local Storage - Dive into HTML5

W3C Local Storage

Web Storage Size Tests