HTML5 web storage, a better local storage than cookies.
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user's
browser.
Earlier, this was done with cookies. However, Web Storage is more
secure and faster. The data is not included with every server request, but used
ONLY when asked for. It is also possible to store large amounts of data,
without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only
access data stored by itself.
Browser Support
Web storage is supported in Internet Explorer 8+, Firefox, Opera,
Chrome, and Safari.
Note: Internet Explorer 7 and earlier versions, do not support web
storage.
localStorage and
sessionStorage
There are two new objects for storing data on the client:
- localStorage -
stores data with no expiration date
- sessionStorage -
stores data for one session
Before using web storage, check browser support for localStorage
and sessionStorage:
if(typeof(Storage)!=="undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
{
// Yes! localStorage and sessionStorage support!
// Some code.....
}
else
{
// Sorry! No web storage support..
}
The localStorage Object
The localStorage object stores the data with no expiration date.
The data will not be deleted when the browser is closed, and will be available
the next day, week, or year.
Example
localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;
Example explained:
- Create a
localStorage key/value pair with key="lastname" and
value="Smith"
- Retrieve the
value of the "lastname" key and insert it into the element with
id="result"
Tip: Key/value pairs are always stored as strings. Remember to
convert them to another format when needed.
The following example counts the number of times a user has
clicked a button. In this code the value string is converted to a number to be
able to increase the counter:
Example
if
(localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that
it stores the data for only one session. The data is deleted when the user
closes the browser window.
The following example counts the number of times a user has
clicked a button, in the current session:
Example
if
(sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
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 throughwindow.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 thatsessionStorage
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 methodlength
Property – Returns the length of number of itemsremainingSpace
Property – Return the remaining storage space in bytes, for the storage objectclear()
Method – Remove all the key/value pairs from DOM Storagekey()
Method – Retrieves the key at specified indexremoveItem()
Method – Remove the key/value pair from DOM StoragesetItem()
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/)