Welcome Text

  The life of a designer is a life of fight: fight against the ugliness.

Friday 15 February 2013

HTML5 Local Storage – Complete Guide Tutorial


TYPES OF WEB STORAGE

Web Storage is a new HTML5 API offering important benefits over traditional cookies. Although the specification is still in W3C draft status, already all major browsers support it.
This means you can start using the API’s sessionStorage and localStorage objects and enjoy their benefits.


Introduction

localStorage is a client-side key-value database, meaning it is stored in the users browser. This means the users data is saved on their machine inside their browser. This also means that their data is only available to them when on that machine and in that browser. Remember that localStorage is per browser not per computer.


The Limitations of Cookies

First, there were cookies. They have been a huge driving factor for the Web since the early days. In both a good and a bad way.
For example, cookies allow us to login automatically to sites we use frequently, such as Gmail and Facebook.
On the other hand, with cookies, our search and browsing history can be tracked andour privacy is a concern.
Another problem with cookies is that they have data-capacity limitations. The data storage limit of cookies in many web browsers is about 4 KB per cookie, based on a deprecated 1997 specification recommending a minimum of 4096 bytes per cookie.
Although most browsers allow 30 to 50 cookies, so if you exceed the 4 KB limit of one cookie you could create another one, this is still a real limitation.
This is why developers usually only store user and/or session identifiers in cookies, and then use server-side databases to store and get the rest of the user data.
Additionally, an often-overlooked side effect of cookies is that they are always sent with every HTTP request (usually even for images) resulting in more data being sent over the wire.


Web Storage and its Advantages

Web Storage picks up where cookies left off. The strength of Web Storage is in at least two things.
First, ease of use for web developers: It has a simple API to get and set key/value pairs (we will get more into this below).
Secondly, the amount of space it provides: the specs default the disk space quota decision to the user agent (i.e. the web browser developers) and most of them offer no less than 5 or 10 MB to be stored per domain. This means we can store more than just basic user/session info on the client-side: user preference settings, localization data, temporary offline storage for batching server writes and much more.
The data being stored can be accessed using JavaScript, which gives you the ability to leverage client-side scripting to do many things that have traditionally involved server-side programming and relational databases.


How to Check the browser support for local storage

if (Modernizr.localstorage) {
  // window.localStorage is available!
} else {
  // no native support for HTML5 storage :(
}


Browser version to Support localstorage

As you might expect with any HTML 5 specification older browsers versions and browser with Javascript turned off do not allow this method. The good news is that all modern browsers support it and will continue to do so. The following browsers support HTML 5 Web Storage:

Internet Explorer 8+
FireFox 3.5+
Chrome 4+
Safari 4+
Opera 10.5+
iOS 2+
Webkit 2+




localStorage and JSON

localStorage is a simple key/value pair database that allows you to store around 5MB of data per domain. Because it doesn't natively support the storage of JSON objects we will need to serialise our data to store it and deserialise it when we want to use it. Here's how we get and set our data in localStorage.

// Store
localStorage.setItem('key', JSON.stringify( value ));

// Fetch
value= JSON.parse( localStorage.getItem('key'));


Primary Methods of localStorage


localStorage.clear()
localStorage.getItem( key )
localStorage.removeItem( key )
localStorage.setItem( key, value )


Coding using HTML5localStorage


Now lets get into some code. Where localStorage differs from cookies or sessionStorage is that the data stored in localStorage is still there even after the browser is closed and is shared across multiple windows. You don’t have to worry about a user deleting the cookies and all their data. A quick note; because of my love for jQuery, I will be using jQuery when using localStorage. However, jQuery is not required to do any of this, I just like how clean it makes everything look. First lets see a simple example of using localStorage.

localStorage.setItem("name", "Amit!"); //saves to the database, key/value
document.write(localStorage.getItem("name")); //Amit!
localStorage.removeItem("name"); //deletes the matching item from the database

Can’t get much easier then that. Line 1 saves a new entry in the local database with the key of ‘name’ and the value of ‘Amit!’. That pair is now stored in your browsers database. Line 2 gets the item from the database with the key of ‘name’. In this case would then return ‘Amit!’. In line 3 we remove the item from the database. Due to browser specific quotas you would want to check for exceptions so you would change line 1 above to the following.

try {
     localStorage.setItem("name", "Amit!"); //saves to the database, "key", "value"
} catch (e) {
     if (e == QUOTA_EXCEEDED_ERR) {
          alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
    }
}

You might also want to check to see if the users browser even supports localStorage and if it doesn’t we can warn them. Now the code above would look like this:

if (!Modernizr.localstorage )// or you can check like this typeof(localStorage) == 'undefined' )
{
    alert('Your browser does not support HTML5 localStorage. Try upgrading.');
} else {
    try {
        localStorage.setItem("name", "Amit!"); //saves to the database, "key", "value"
    } catch (e) {
          if (e == QUOTA_EXCEEDED_ERR) {
               alert('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
        }
    }

    document.write(localStorage.getItem("name")); //Amit!
    localStorage.removeItem("name"); //deletes the matching item from the database
}


How to check local storage key-value using firebug tools


1.Press F12 or open your browser firebug.
2.Go to the DOM tab
3.scroll down to and expand localStorage
4.Expand the localStoragetab.Now you can see all the key-value saved in the localStorage.
5.right click item you wish to delete or edit and do whatever you want.

If your using Safari or Chrome then you have a much better option. You are able to view these databases directly in the developer tools. Opening the Developer Tools you will notice the last item is Databases, clicking this will show you all databases, localStorage and sessionStorage info.


Practical uses of localstorage


Now we know about the local storage. But the main question is where we’ll use this. The answer of this question is not universal and it depends upon the requirements and type of projects.I can give you some example where localstorage can be useful.

1. In multipage registration form you can store partial data in the localstorage. When user click on the submit button then you will take the value from localstorage and save it in database.
It will decrease the number of server call and unwanted entry in the database to make your application faster.

 2. In shopping cart you can use local storage. You can store the shopping cart items in the localstorage first. When the user checkout the shopping cart then you will save the important data in the database. This will also decrease the number of server call and unwanted entry in the database to make your application faster.

3. In the previous article I’ve already discussed about the offline application in HTML5 and localstorage will play a key role in that aspect. When web application is offline we can store all the data in localstorage and when application becomes online we can store those data from localstorage to database. 



Thanks for reading this blog.Hope you enjoy it.Follow this blog to get updated about design stuff.