Tuesday 10 January 2012

HTML5 Web Storage



HTML5 offers two new objects for storing data on the client:


  • localStorage - stores data with no time limit
  • sessionStorage - stores data for one session
Earlier, this was done with cookies. Cookies are not suitable for large amounts of data, because they are passed on by EVERY request to the server, making it very slow and in-effective.
In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website's performance.
The data is stored in different areas for different websites, and a website can only access data stored by itself.
HTML5 uses JavaScript to store and access the data.

       Web Storage and DOM Storage (Document Object Model) are web application software methods and protocols used for storing data in a web browser. Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP Request Header. There are 2 main web storage types, local storage and session storage, behaving like Persisted Cookies and Session Cookies accordingly.
Web storage is being standardized by the World Wide Web Consortium (W3C). It was originally part of the HTML 5 specification, but is now in a separate specification. It is supported byInternet Explorer 8, Mozilla-based browsers (e.g., Firefox 2+, officially from 3.5), Safari 4,Google Chrome 4 (sessionStorage is from 5), and Opera 10.50. As of 14 July 2010 only Opera supports the storage events.

Simple Web Storage Facts
  • Values can be any data type supported by the structured clone algorithm.
  • User agents should not expire data from a browsing context's session storage areas, but may do so when the user requests that such data be deleted, or when the UA detects that it has limited storage space, or for security reasons.
  • Storage items are available on the entire domain.

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

Storage Size

Web Storage provides far greater storage capacity (5MB per domain in Mozilla Firefox, Google Chrome, and Opera, 10MB per storage area in Internet Explorer) compared to 4KB (around 1000 times less space) available to cookies.


Client-side interface

Unlike cookies, which can be accessed by both the server and client side, Web storage falls exclusively under the purview of client-side scripting. Web storage data is not transmitted to the server in every HTTP request, and a web server can't directly write to Web storage, but can of course issue read and write requests.


Local and session storage

Web storage offers two different storage areas—local storage and session storage—which differ in scope and lifetime. Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.


Interface and Data model

Web storage currently provides a better programmatic interface than cookies exposing an associative array data model where the keys and values are both strings. An additional API for accessing structured data, perhaps based on SQL, is being considered by the W3C Web Applications Working Group.

sessionStorage

// Store value on browser for duration of the session
sessionStorage.setItem('key', 'value');
 
// Retrieve value (gets deleted when browser is closed and re-opened)
alert(sessionStorage.getItem('key'));


localStorage

// Store value on the browser beyond the duration of the session
localStorage.setItem('key', 'value');
 
// Retrieve value (works even after closing and re-opening the browser)
alert(localStorage.getItem('key'));


Accessing data for a particular domain

The following code can be used to retrieve all values stored in local storage for a particular domain (the domain for the web page that is being browsed).
This JavaScript code can be executed using development tools available in most modern browsers such as the IE Developer Toolbar, Chrome Developer Tools, or Firebug extension in Firefox.:
var output = "LOCALSTORAGE DATA:\n------------------------------------\n";
if (localStorage) {
    if (localStorage.length) {
       for (var i = 0; i < localStorage.length; i++) {
           output += localStorage.key(i) + ': ' + localStorage.getItem(localStorage.key(i)) + '\n';
       }
    } else {
       output += 'There is no data stored for this domain.';
    }
} else {
    output += 'Your browser does not support local storage.'
}
alert(output);


Data Types

It is important to note that only strings can be stored via the Storage API. Attempting to store a different data type will result in an automatic conversion into a string in most browsers. Conversion into JavaScript Object Notation (JSON), however, allows for effective storage of JavaScript objects.
// Store an object instead of a string
localStorage.setItem('key', {name: 'value'});
alert(typeof localStorage['key']); // string
 
// Store an integer instead of a string
localStorage.setItem('key', 1);
alert(typeof localStorage['key']); // string
 
// Store an object using JSON
localStorage.setItem('key', '{"name":"value"}');
alert(eval(localStorage['key']).name); // value


Nomenclature

The W3C draft is titled "Web Storage", but "DOM storage" is also a commonly used name.
The "DOM" in DOM storage doesn't literally refer to the Document Object Model. "The term DOM is used to refer to the API set made available to scripts in Web applications, and does not necessarily imply the existence of an actual Document object..."


Web Storage Management

Storage of Web Storage Objects is enabled per default in Mozilla Firefox and SeaMonkey, but can be disabled by setting the "about:config" parameter "dom.storage.enabled" to false.
Mozilla Firefox stores all Web Storage objects in a single file named webappsstore.sqlite. The sqlite3 command can be used to show the elements stored therein.
There are browser extensions/add-ons for Google Chrome and Mozilla Firefox available that let the user deal with web Storage, such as "Click&Clean", "BetterPrivacy" which can be configured to remove the whole Web Storage automatically on a regular basis.

No comments:

Post a Comment