Introduction to HTML5 DOMStorage API with Example

HTML5 is a standard for structuring and presenting content on the World Wide Web. The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash and Microsoft Silverlight. HTML5 introduces a number of new elements and attributes that reflect typical usage on modern websites. Some of them are semantic replacements for common uses of generic block (<div>) and inline (<span>) elements, for example <nav> (website navigation block) and <footer> (usually referring to bottom of web page or to last lines of html code). Other elements provide new functionality through a standardized interface, such as the multimedia elements <audio> and <video>. In addition to specifying markup, HTML5 specifies scripting application programming interfaces (APIs). Existing document object model (DOM) interfaces are extended and de facto features documented.

What is DOM Storage?

DOM Storage is a way to store meaningful amounts of client-side data in a persistent and secure manner. It is a W3C draft which covers exactly how saving information on the client-side should be done. It was initially part of the HTML 5 specification, but was then taken out to be independent. Web Storage, or the somewhat confusing popular name DOM Storage, is a great way to save information for the current session and window, or for returning users. The DOM Storage provides mechanism to securely store data in the form of key/value pairs and later retrieve to use. The main goal of this feature is to provide a comprehensive means through which interactive applications can be built (including advanced abilities, such as being able to work “offline” for extended periods of time). DOM Storage provides a powerful way of storing and retrieving data at client side using JavaScript like APIs which are easy to use.

Scope of DOM Storage

DOM Storage provides different mechanism to store the client data using in-built storage objects which provides wide range of scope. For example, using DOM Storage it is possible to store data for a Session of user request, or for all the pages of a website. DOMStorage storage mechanism is accessed by global variables of window object. Following are the objects available which provides different scope of data storage.

sessionStorage

The sessionStorage object can be accessed by directly referencing it by name of through window.sessionStorage. This is a global object (sessionStorage) that maintains a storage area that’s available for the duration of the page session. A page session lasts for as long as the browser is open. Opening a page in a new tab or window will cause a new session to be initiated. Note that sessionStorage can survive browser restart thus it is most useful for hanging on to temporary data that should be saved and restored if the browser is accidentally refreshed. Example: Save a string value “Hello, World” and display it on browser refresh.
//Store the data in sessionStorage object sessionStorage.hello = “Hello, World!”; //Retrieve the data from sessionStorage object on //browser refresh and display it window.onload = function() { if(sessionStorage.hello) alert(sessionStorage.hello); }
Code language: JavaScript (javascript)

localStorage

The localStorage object is useful when one wants to store data that spans multiple windows and persists beyond the current session. The localStorage provides persistent storage area for domains. For example: data stored at localStorage['viralpatel.net'] can be retrieved by any script hosted at level Viralpatel.net. Similarly data stored at localStorage['net'] can be accessed by scripts at any .net TLD level websites. Data stored as localStorage[''] can be accessed by all the pages on all sites. Example: Following script will store a value hello at Viralpatel.net level. Thus all the scripts hosted at Viralpatel.net and its sub-domain level can both read and write the values.
//Store the data in localStorage object localStorage['viralpatel.net'].hello = "Hello, World!";
Code language: JavaScript (javascript)

DOM Storage API

DOM Storage objects sessionStorage and localStorage provides certain useful properties and methods API. Following are the list of such APIs.
  • getItem() Method – Get the value of item passed as key to the method
  • length Property – Returns the length of number of items
  • remainingSpace Property – Return the remaining storage space in bytes, for the storage object
  • clear() Method – Remove all the key/value pairs from DOM Storage
  • key() Method – Retrieves the key at specified index
  • removeItem() Method – Remove the key/value pair from DOM Storage
  • setItem() Method – Sets a key/value pair

Comparing HTTP Cookies with DOM Storage

Following are few comparison points between HTTP Cookies and DOM Storage.
  • HTTP Cookies can store limited amount of user data (e.g. 4KB) where as modern browser such as IE 8 supports up to 10MB of data being stored with DOM Storage
  • Cookies limits the accessibility of data to a certain domain name or a URL path where as DOM Storage can limit the access to a certain domain name, or to domain TLD (like .org) or for given user session.
  • The keys stored with HTTP Cookies can be retrieved by using APIs. It is possible to iterate through all the key/value pairs in HTTP Cookies. Whereas in DOM Storage it is not possible to iterate through keys. Data cannot be retrieved unless key is known.
  • Data stored as HTTP Cookies can be retrieved at Server as this data is passed with request. Whereas the DOMStorage is more of client data and is not possible to retrieve it directly at server side.

Web Browser Support

Currently modern browsers such as Firefox 3.5, Internet Explorer 8 and Safari 4 fully support the DOM Storage specification. Following are the list of browsers and their corresponding values such as Storage size, Support, Survive Browser Restart.
Browser Storage Size Storage Support Survives Browser Restart
Firefox 2 5 MB Yes No
Firefox 3 5 MB Yes No
Firefox 3.5 5 MB Yes Yes
Safari 3 No No
Safari 4 5 MB Yes Yes
Chrome 2 No No
IE 8 10 MB Yes Yes
Opera 10 No No

Demo Application

Let us demonstrate the use of DOMStorage API and create a demo application.

Application Requirement

Application has a form called Client Form with some input elements. The requirement is to persist the values of the form in case the page is accidentally refreshed and restore the values back.

User Interface

Demo application will have a simple input form to enter Client information. The form will have few input fields to capture user input. In case of accidental refresh of the webpage the values should be persevered in the form.

Source Code

Following is the HTML Source code of web page containing Client Form:
<HTML> <HEAD> <TITLE>DOMStorage - Sample Application </TITLE> </HEAD> <BODY> <H2>Client Form </H2> <br/> <form name="clientForm" id="clientForm"> <table> <tr> <td>First Name </td> <td> <input type="text" name="firstname"/> </td> </tr> <tr> <td>Last Name </td> <td> <input type="text" name="lastname"/> </td> </tr> <tr> <td>Date of Birth </td> <td> <input type="text" name="dob"/> </td> </tr> <tr> <td>Gender </td> <td> <input name="gender" type="radio" value="M">Male </input> <input name="gender" type="radio" value="F">Female </input> </td> </tr> <tr> <td>Designation </td> <td> <select name="designation"> <option value="0">Software Engineer </option> <option value="1">Sr. Software Engineer </option> <option value="2">Technical Architect </option> </select> </td> </tr> <tr> <td colspan="2"> <br/> <input name="submit" type="button" value="Submit"/> <input name="reset" type="reset" value="Reset"/> </td> </tr> </table> </form> <script type="text/javascript" src="domstorage-persist.js"></script> </BODY> </HTML>
Code language: HTML, XML (xml)
Following is JavaScript code (content of domstorage-persist.js)
/** * Filename: domstorage-persist.js * Author: viralpatel.net * Description: HTML code independent form persistent * Usage: persist(<form object>); */ function persist(form) { /* * In case of page refresh, * store the values of form to DOMStorage */ window.onbeforeunload = function () { var str = serialize(form); try { sessionStorage[form.name] = str; } catch (e) {} } /* * If the form was refreshed and old values are available, * restore the old values in form */ window.onload = function () { try { if (sessionStorage[form.name]) { var obj = eval("(" + sessionStorage[form.name] + ")"); for (var i = 0; i < obj.elements.length - 1; i++) { var elementName = obj.elements[i].name; document.forms[obj.formName].elements[obj.elements[i].name].value = obj.elements[i].value; } } } catch (e) {} } } /* * Convert form elements into JSON String */ function serialize(form) { var serialized = '{ "formName":"' + form.name + '", "elements": ['; for (var i = 0; i < form.elements.length; i++) { serialized += '{'; serialized += '"name":"' + form[i].name + '",'; serialized += '"value":"' + form[i].value + '"'; serialized += '},'; } serialized += '{"name":0, "value":0}'; serialized += '] }'; return serialized; } /* * Make the Client Form persistable. * i.e. Persist its values in case of page refresh */ persist(document.clientForm);
Code language: JavaScript (javascript)

References

Further Reading

The given article focuses on the latest mechanism of DOMStorage being standardized by World Wide Web Consortium (W3C) as part of HTML5. There are few other similar technologies available which can be leveraged to store offline data in browser. Users who are interested in browser based storage are highly advisable to read about following technologies.

View Comments

    • Hi, It seems that there is no Servlet API for this as of now. All I can think of is to put domstorage value in a hidden html element and access it in Servlet via request parameter. Though this is not clean but atleast it will work. Hope future Servlet specifications have dedicated APIs to access DomStorage data.

  • Hi,
    I studied technologies in your website. Its easy to learn.Thanks for your good work.
    i have one doubt that i want to retrieve data's from DB and i want to store it on client side until the session end. I am using spring and jsp. Pls help. Thanks in advance.

Share
Published by
Viral Patel
Tags: domstorage html html5 Web 2.0

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago