HTML5 - Web Storage and Offline Capabilities

In this blog, I will try to understand the new concepts with HTML5, namely, web storage which allows storing data on client side easier and offline capabilities which allow web apps to function even if they are offline.
Web Storage
There are 2 types of storage capabilities that we can use
  • Local 
    • stored forever (until we delete either through app or clear temp files)
    • similar to cookies
    • accessed through window.localStorage property
    • is a collection of key-value pairs
    • can be removed using window.localStorage.removeItem(key) function
    • Whole storage can be cleared by using the window.localStorage.clear() function
    • The amount of storage used can be tracked by using the window.localStorage.length property
    • The amount of storage space remaining can be tracked by using the window.localStorage.remainingSpace property
    • If the space is exceeded, an exception of type QUOTA_EXCEEDED_ERR is thrown
  • Session
    • similar to local but data is lost once the session is over i.e, user closes the browser or user session ends.
    • accessed through window.sessionStorage property
    • is a collection of key-value pairs
    • can be removed using window.sessionStorage.removeItem(key) function
    • Whole session can be cleared by using the window.sessionStorage.clear() function
    • The amount of storage used can be tracked by using the window.sessionStorage.length property
    • The amount of storage space remaining can be tracked by using the window.sessionStorage.remainingSpace property
    • If the space is exceeded, an exception of type QUOTA_EXCEEDED_ERR is thrown
The storage component of HTML5 also exposes an event whenever any storage functionality happens. This event can be tapped into by using the window.addEventListener("storage", function (e) { // do something }). The argument e provides access to which key fired the event, old value, new value etc.

// storage event
    window.addEventListener("storage", function (e) {
        alert("storage event fired. Key = " + e.key +
            "\nNew Value: " + e.newValue +
            "\nOld Value: " + e.oldValue +
            "\nURL: " + e.url +
            "\nStorage Area: " + e.storageArea);
    }, false);

    // local storage
    if (localStorage.PageCount)
        localStorage.PageCount = Number(localStorage.PageCount) + 1;
    else
        localStorage.PageCount = 1;
    $('#locStore').val(localStorage.PageCount);

    if (localStorage.SomeValue)
        $('#locStore1').val(localStorage.SomeValue);

    $('#btnSaveLocStore1').click(function () {
        localStorage.SomeValue = $('#locStore1').val();
    });

    $('#btnDelLocStore1').click(function () {
        localStorage.removeItem("SomeValue");
        $('#locStore1').val("");
    });

    // session storage
    if (sessionStorage.PageCount)
        sessionStorage.PageCount = Number(sessionStorage.PageCount) + 1;
    else
        sessionStorage.PageCount = 1;

    $('#sessStore').val(sessionStorage.PageCount);

Here, I am providing some jQuery code which explains how to use the storage capabilities of HTML5. The first part is listening to the storage event. Currently, this only works in IE9. Afterwards, I use the local storage to keep track of page counts on this machine and also a user-defined value. I also provide a delete button to delete the local storage data. After that, there is a similar example for session storage. But that data is lost once you close the browser. The local storage data persists even if you close the browser. Here, is an image of the HTML form.


Offline
HTML5 provides capabilities to control a web app even when the user is offline. HTML5 provides the developer some easy rules to work with so that they can create apps that work when the user is offline and then once the user comes online, it can do some work to make the data sync with the server. Following are some of the pointers to get an offline app working -
  • Any app that should work offline should have a manifest file defined. It is this file that HTML5 looks for to provide offline functionality.
  • The rules for manifest file are as below -
    • first line in this file must be CACHE MANIFEST
    • second line identifies the version. This line is used to identify whether the version of files has been changed or not.
    • second section starts with the word CACHE
    • here we provide the list of all files that we want to be cached.
    • It is these files that get downloaded and stored on the client side when any change in the version is detected
    • if any one of the file download fails, HTML5 treats as the whole operation has failed.
    • third section is NETWORK
    • here we provide an exclusion list. This is a list of files that should never be cached.
    • fourth section is FALLBACK
    • here you can define a map to tie up online and offline pages. For ex. if you want to show an ABC page when you are online and an ABC-fallback page when you are offline, you can do so by providing a mapping here similar to /ABC /ABC-fallback
    • we also need to make sure that the ContentType of manifest file is set to "text/cache-manifest" and ResponseEncoding is set to "utf-8"
  • the offline api can be accessed using window.applicationCache property
    • there are few browser events that we can tap into as well. These events are called at certain stages -
      • First time loading
        • Checking (window.applicationCache.onchecking)
        • Downloading (window.applicationCache.ondownloading)
        • Progress
        • Cached (window.applicationCache.oncached)
      • subsequent loads (manifest hasn't changed)
        • Checking
        • No Update (window.applicationCache.onnoupdate)
      • subsequent loads (manifest has changed)
        • same as first time loading
      • at any given time, we can have the following cache states
        • 0 - uncached
        • 1 - idle
        • 2 - checking
        • 3 - downloading
        • 4 - updateready (window.applicationCache.onupdateready) - this happens when download has been successful and browser can be notified that the app is ready to be reloaded.
        • 5 - obsolete (window.applicationCache.onobsolete)
      • If we want to provide a manual action to update the application, we just need to call location.reload()
      • To do an automatic update we just need to call location.reload() in onupdateready() to trigger the reload.