Wednesday, January 18, 2012

HTML5 series part 1: localStorage

HTML5 introduces client-side storage API which aims to cover the limitations of cookie and provide  much more.  in this article, i am going to explore about browser cookies, their limitations and how HTML5 overcomes these with client-side storage.

Legacy of HTTP cookie:
An HTTP cookie is a set of key/value pairs that an web server requests web browsers to store on local disk. when browser makes further requests to the server, it wraps all the cookie information in HTTP request header as long as the following conditions are met: ( ref: rfc2109)
1.The cookie is not expired.
2. The requested domain is same or subdomain of cookie storing domain .
3. The requested path is same of subpath of cookie storing domain.

browser  deletes cookie data when cookie expires.

Limitations of cookie:
 1. most current browsers limit cookie size to 4KB.
 2. Number of cookies in a domain is limited to 300
 3. when a site uses cookie, then every request must include all cookie data in HTTP header which is a performance issue.
4. cookie data is stored as plain text in client disk which can cause cookie/session hijacking.
5. cookie cannot differentiate between two different instances of same web application running in two different tabs or windows.

Age of client-side storage:
According to the web storage specification, web storage is intended to solve two cases that are not handled well by cookies:
1. The first is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.
2. The second storage mechanism is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, web applications may wish to store megabytes of user data, such as entire user-authered documents or a user's mailbox, on the client side for performance reasons.

Unlike cookie, web storage data is stored in the client by the browsers based on retention policies. Benefits are obvious:
1. data doesn't pass through HTTP request/response. bandwidth is saved.
2. as data isn't passed through network, this is relatively secure.this notion of security has some other advantages. This means that due to the inherent security feature, HTTPs connection can use plain HTTP. Because it wont need  to encrypt data since data is stored in client-side. Since HTTPs has only 10% of performance comparing with HTTP.
3. no download time means better user experience
4. with the help of web storage, surfing same web sites using more than one account simultaneously wont be a tough task.  You can experience this right now on google sites.
5. There is no 4KB limitation, web site will enjoy much more flexibility in storing large data in client.

localStorage API:
localStorage is a handy API included in HTML5 spec that gives web developers any easy to use 5MB store on the client's local machine. It's a simply key/value dictionary that allows developers to store primitive data types like integer, string etc. storing objects requires serialization into json format. localStorage doesn't provide transaction facilities. So wise usage can save you from race conditions.
data storing and retrieval is simple:

//save a value to localStorage
localStorage.setItem('key', 'value');
localStorage.key = value;
myObject = {a:1, b:2, c:3};
localStorage.setItem('key', JSON.stringfy(myObject));

//retrieve a value 
var value = localStorage.key;
var value = locaStorage.getItem('key');
var myStorageObject = JSON.parse(localStorage.getItem("key"));
//reset storage
localStorage.clear();

//to remove an item
localStorage.removeItem('key');

Important features of localStorage:
1. localStorage values on Secure (SSL) pages are isolated:
browsers isolates localStorage values based on HTML5 origin (scheme +hostname+unique port). so http://xyz.com is separated from https://xyz.com. firefox provides  globalStorage doesn't follow this distinction. 
2. sessionStorage values can survive browser restarts if browser impements session restore feature.
3. localStorage values created in "incognito" or private browsing mode are isolated. they will be gone as soon as the session ends.
4. localStorage quota for a site is 5 MB. it cannot be expanded. alternative means are available in the form of indexeddb and web SQL database.
//check if quota limited exceeded.
try{
     localStorage.setItem('key', value);
}catch(e){
      if(e== QUOTA_EXCEEDED_ERR) alert(file is too large);
}
5. for older IE browsers, localStorage feature can be implemented using IE-only feature userData.
//checking if localStorage support is available.
var supported = false;
 try{
    if(window['localStorage']!=null) supported = true;
}catch (e){
     supported = false;
}

for browser support issue, visit http://www.quirksmode.org/dom/html5.html

No comments:

Post a Comment