Friday, December 9, 2011

HTML5 - LocalStorage

One of the most useful feature of HTML 5 for the mobile and web developers is Local Storage. LocalStorage is a handy API included in the "HTML5" wave that gives developers an easy to use 5MB store on an users local machine. Local Storage is simple API's developers can use to store data and use it later in an offline mode.
For example, if you are on a web page and by mistake you close it or navigate to another page while filling some useful information in the form, all the information input in the form is lost...What a bummer :(

By nature, web html pages do not persist data, it was hard to persist the information. Local Storage API's has been designed to address this issue.

Local Storage is a simple key/value dictionary with a simple API to match:
simple code snippet would look like:-
//To Save a value to localStorage
localStorage.setItem('key', 'value-to-be-saved');
//OR
localStorage.key = 'string value-to-be-saved';

//Get the value back out of localStorage
localStorage.getItem('key');
//OR
localStorage.key;

//Clear all localStorage values
localStorage.clear();


I hope above is very simple and does not need any explanation.

Difference between Local Storage and Session Storage
Joining LocalStorage in the HTML5 spec is also SessionStorage. It provides an identical API, but a different "retention policy." As the name implies, values in SessionStorage should only survive a single browser session (not server session).

How Local Storage Works

let's take a few moments and first learn how local storage actually works.

At the core, each of your pages has a reference to a global object called localStorage:
If you step inside this object, there is a defined key-value pair structure that is well designed for storing data. The way it stores the data is by neatly organizing them into rows of key/value pairs.

In the above localStorage visualization, you can see that there are three pieces of data:

firstName with a value of Vikrant
lastName with a value of Bains
location with a value of Los-Angeles

Think of each row as one contiguous piece of data made up of a key and a value. The key serves as the identifier to your data, and the value is the information associated with it.

An important thing to note is the scope of this data. The localStorage data is domain-specific where you have only one instance per domain. In other words, any data inside your localStorage object is available only when you are referring to it from a page hosted within the same domain.

Some important facts:-
1. LocalStorge values on Secure (SSL) pages are isolated
Browsers isolate LocalStorage values based on scheme + hostname + unique port (also known as an HTML5 Origin). Hostname is expected, since you don't want malicious websites to have access to other websites' LocalStorage data. But scheme (i.e. http and https)?

The result of this separation means that a value saved to LocalStorage on http://abc.com cannot be accessed by pages served from https://abc.com (and vice versa). There is some good reason for this (I suppose), especially in the case of isolating values created during a secure session from unsecured sessions. But since LocalStorage should never be a place for storing sensitive data,it makes this little strange as well...

2. SessionStorage values survive some browser restarts

SessionStorage, unlike LocalStorage, is not designed for long-term persistence of values in the user's browser. Instead, values in SessionStorage are destroyed when a browser session ends, which is usually when the browser window is closed.

There is an exception, though.

When a browser provides a "Restore Session" feature, usually designed to help users quickly recover from a browser/computer crash, values in SessionStorage will be restored, too. So while it's a new "session" on the server, from the browser's perspective, it's a continuation of a single session across a browser restart.

3. LocalStorage values created in "incognito" or Safe mode are isolated

When you fire-up a browser in private/incognito/safe mode , it will create a new, temporary database for LocalStorage values. That means anything saved to LocalStorage will be destroyed when the private browsing session is closed, making LocalStorage behave more like SessionStorage.

Additionally, since a browser's "Session Restore" feature does not re-open private mode sessions, anything created in SessionStorage will also be lost after the browser window is closed. Really, in short, any data put in Local or SessionStorage during a private browsing session will be lost as soon as the browser window is closed (intentionally or not).

4. LocalStorage quotas cannot be made bigger than 5MB

LocalStorage is not supposed to be the primary form of in-browser storage with HTML5 (IndexDB will eventually come along to provide that), but some apps may want more than the default 5MB LocalStorage provides. There is NO way to expand LocalStorage quotas.

Technically, the LocalStorage origin restriction does not block sub-domains of the same host (using the same scheme and port) from accessing the same LocalStorage object. As a result, some browsers have exposed a workaround that grants "a1.website.com" and "a2.website.com" their own 5MB LocalStorage quotas. And since both sites are on the same origin, they can access each others values.

5. LocalStorage can be used on older browsers (including IE)

Legacy browsers can use this feature as well. Fortunately, LocalStorage is incredibly well supported in Class A browsers. It's natively available in IE8+ (!), Firefox 3.5+, and Chrome 4+.

Simple self explanatory code snippets


Detecting Whether Local Storage Exists or Not
function isLocalStorageSupported {

try {

var supported = false;
if (window['localStorage'] !== null)
{

supported = true;

}
return supported;

} catch(e) {

return false;

}

}

Dealing with File Size

You have a fixed size of 5 MB for each domain your local storage is tied to. If you try to add more data even after you have exceed your quota, a QUOTA_EXCEEDED_ERR exception will be thrown.

Handling this exception is pretty straightforward:

try {

localStorage.setItem("key", "some data");

} catch (e) {

if (e == QUOTA_EXCEEDED_ERR) {

// do something nice to notify your users

}

}

All you need to do is wrap any code that tries to add more data to your localStorage into a try/catch statement. While just catching the exception will prevent users from seeing a script error, matching the exception to the QUOTA_EXCEEDED_ERR exception will allow you to go one step further and let your users know why they were not able to save the data to local local storage.

Removing Data

There are two extremes to removing data from your localStorage object. You can remove everything scorched earth style, or you can selectively remove a key/value pair individually.

Because scorched earth is an awesome game, let's look at it first. To remove everything from your localStorage for your current domain, you can call the clear() method:

localStorage.clear();

This will remove all traces of any data you may have stored for this domain, so use it cautiously if you have several pages on your site that each write to the local storage independently.

To remove only select key/value entries from your local storage, you can use removeItem() and pass in the key name associated with the data you wish to remove:

localStorage.removeItem("location");

In this example, the location key and its value will be deleted while leaving all of the other data intact.

Retrieving Data

To retrieve data stored in your localStorage object, you use the getItem method:

var firstNameData = localStorage.getItem("firstName");
var lastNameData = localStorage.getItem("lastName");
var locationData = localStorage.getItem("location");

The getItem method takes only the key as an argument, and it returns the value associated with that key. If the key you pass in does not exist, a value of undefined is returned.
Note

If you don't like using the getItem or setItem methods, you can bypass them by using object notation for setting and retrieving data:

// storing data
localStorage[key] = value;
// retrieiving data
var myData = localStorage[key];

Adding Data

To add data to your local storage object, all you need is a key and a value...and the setItem method that lives on your localStorage object:

localStorage.setItem('firstName', 'Vikrant');
localStorage.setItem('lastName', 'Bains');
localStorage.setItem('location', 'Los-Angeles');

In each line, we are adding a key/value pair to our localStorage object. The setItem method takes two arguments. The first argument is the key, and the second argument is the value.

Conclusion- Local Storage is very simple to use but like any other project, careful design decisions needs to be made before implementing it. Merely simplicity of use should not be a driving factor to use this

No comments: