Introduction to HTML5 DOMStorage API with Example
Join the DZone community and get the full member experience.
Join For Free
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); }
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!";
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>
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);
References
- W3C: Web Storage draft standard (http://dev.w3.org/html5/webstorage/)
- Mozilla Developer Center: DOM Storage (https://developer.mozilla.org/En/DOM:Storage#Description)
- MSDN: Introduction to DOM Storage ( http://msdn.microsoft.com/en-us/library/cc197062(VS.85).aspx#_dom)
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.
- HTTP Cookies (http://www.microsoft.com/info/cookies.mspx)
- DOMCached – A memcached like caching system for JavaScript using DOM storage (http://www.domcached.com)
- Google Gears (http://gears.google.com/)
- Adobe Flash – Local Shared Objects (http://www.adobe.com/products/flashplayer/articles/lso/)
From: http://viralpatel.net/blogs/2010/10/introduction-html5-domstorage-api-example.html
Opinions expressed by DZone contributors are their own.
Comments