Wednesday, May 16, 2012

HTML5 Web Storage

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.

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..
 }

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.

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.

Where to Use Web Storage?

Some examples of implementation scenarios include storing the data for an online to-do list (then pushing to the server in intervals instead of in real-time) or saving products that the user places in his shopping cart. The data can be made available between page requests, multiple browser tabs, and also between browser sessions using localStorage.

Your apps can actually be used offline completely using localStorage. Data can then be sent and stored server-side when the user is online again.
From another perspective, Web Storage can be a great performance win when some static data is stored on the client to minimize the number of subsequent requests. Even images can be stored in strings using Base64 encoding.

For the examples mentioned above, it makes sense to use localStorage. You may be wondering, then, when you should opt for sessionStorage.

In some cases, you simply want to get rid of the data as soon as the window is closed. Or, perhaps, you don’t want the application to interfere with the same application that’s open in another window (e.g. when running two instances of a Scrabble game or running multiple unit tests simultaneously, you don’t want data to collide). These scenarios are served best with sessionStorage.

HTML5 Web Storage Methods
  • setItem(key,value): adds a key/value pair to the sessionStorage object.
  • getItem(key): retrieves the value for a given key.
  • clear(): removes all key/value pairs for the sessionStorage object.
  • removeItem(key): removes a key/value pair from the sessionStorage object.
  • key(n):retrieves the value for key[n].

Setting a Key/Value
There are two different methods for setting information into sessionStorage & localStorage:
sessionStorage.setItem('someKey','someValue');
localStorage.setItem('someKey','someValue');
...or you could just use the shortcut method:
sessionStorage.someKey = 'someValue';
localStorage.someKey = 'someValue';

Getting a Value
There are two methods to retrieve a key/value pair as well:
sessionStorage.getItem('someKey'); //returns 'someValue'
localStorage.getItem('someKey');
...or simply reference the sessionStorage object:
sessionStorage.someKey; //returns 'someValue'
localStorage.someKey;

Removing a Key/Value
sessionStorage.removeItem('someKey');
localStorage.removeItem('someKey');
All you need to do is provide the key to the removeItem method.

Clearing Storage
sessionStorage.clear(); //everything gone
localStorage.clear();
A simple clear call -- that's it.

EXAMPLE

This is an example to demonstrate the usage of localStorage and sessionStorage objects accross different browsers.

//webstorage.html
<html>
<head>
<script type="text/javascript">
function loadPrev(){
if(typeof(Storage)!="undefined"){
try{
if(localStorage.getItem('name')){
var tag="<table border='1px'><tr><th>Name</th><th>Age</th><th>Sex</th></tr>";
tag=tag+"<tr><td>"+localStorage.getItem('name')+"</td><td>"+localStorage.getItem('age')+
"</td><td>"+localStorage.getItem('sex')+"</td></tr></table>"
document.getElementById('localStorage').innerHTML=tag;
}
else
document.getElementById('localStorage').innerHTML="Nothing to display";
}
catch(err){
document.getElementById('localStorage').innerHTML="Your browser does not support this feature";
}
try{
if(sessionStorage.getItem('name')){
var tag="<table border='1px'><tr><th>Name</th><th>Age</th><th>Sex</th></tr>";
tag=tag+"<tr><td>"+sessionStorage.getItem('name')+"</td><td>"+sessionStorage.getItem('age')+"</td><td>"+sessionStorage.getItem('sex')+"</td></tr></table>"
document.getElementById('sessionStorage').innerHTML=tag;
}
else
document.getElementById('sessionStorage').innerHTML="Nothing to display";
}
catch(err){
document.getElementById('sessionStorage').innerHTML="Your browser does not support this feature";
}
}
else{
document.getElementById('localStorage').innerHTML="Your browser does not support this feature";
document.getElementById('sessionStorage').innerHTML="Your browser does not support this feature";
}
}
function webstore(){
if(typeof(Storage)!="undefined"){
var name=document.getElementById('name').value;
var age=document.getElementById('age').value;
var sex=document.getElementById('sex').value;
var storage=document.getElementById('storage').value;
if(storage=="localStorage"){
localStorage.setItem('name',name);
localStorage.setItem('age',age);
localStorage.setItem('sex',sex);
}
else if(storage=="sessionStorage"){
sessionStorage.setItem('name',name);
sessionStorage.setItem('age',age);
sessionStorage.setItem('sex',sex);
}
loadPrev();
}
}
function clearStorage(){
var res=confirm("Are you sure about clearing the localStorage and sessionStorage data?");
if(res){
try{
localStorage.clear();
sessionStorage.clear();
loadPrev();
}catch(err){
loadPrev();
}
}
}
</script>
</head>
<body onload="loadPrev()">
<table width="100%"  border="1px">
<tr><th>Form</th><th>Local Storage</th><th>Session Storage</th></tr>
<tr>
<td style="width :40%" align="center">
<span>
<table>
<tr><td>Name</td><td><input type="text" id="name" placeholder="Enter Name"/></td></tr>
<tr><td>Age</td><td><input type="text" id="age" placeholder="Enter Age"/></td></tr>
<tr>
<td>Sex</td>
<td>
<select id="sex" style="width :100%">
<option>Male</option>
<option>Female</option>
</select>
</td>
</tr>
<tr>
<td>Storage Type</td>
<td>
<select id="storage" style="width :100%">
<option>localStorage</option>
<option>sessionStorage</option>
</select>
</td>
</tr>
<tr><td><input type="button" value="Store Value" onclick="webstore()"/></td><td><input type="button" value="Clear Storage" onclick="clearStorage()"/></td></tr>
</table>
</span>
</td>
<td style="width :30%" align="center">
<span id="localStorage">
</span>
</td>
<td style="width :30%" align="center">
<span id="sessionStorage">
</span>
</td>
</body>
</html>

Test across different browsers

Internet Explorer



Mozilla Firefox



Opera





Safari



Google Chrome





Browser compatibilities:
From the observations made from the test application the conclusions are as follows
Browser
localStorage
sessionStorage
Internet ExplorerNoNo
Mozilla FirefoxYesNo
OperaYesYes
Apple SafariYesYes
Google chromeYesYes

No comments:

Post a Comment