Monday, 9 December 2013

WebStorage in HTML5

In this module I am going to discuss Web Storage in HTML5

What Is Web Storage?
With HTML5 web storage, websites can store data on a users local computer

Now No More Cookies concept in HTML5
We had to use Javascript cookies in the past to achieve this functionality.

How It Differs From Cookies
·         More secure
·         Faster
·         Stores a larger amount of data
·         The stored data is not sent with every server request. It only is included when asked for. This gives a big advantage over cookies

Detecting HTML5 Storage Support
function supports_html5_storage() {
       try {
          return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) { 
               return false;
        }
}
With Modernizr (Recommended):
if (Modernizr.localstorage) {
        // Local storage available
} else {
       // No local storage available
}

localStorage( ) & sessionStorage()
There are 2 types of web storage objects, local and session
Difference:
localStorage – Stores data with no expiration date
How It Works
sessionStorage – Stores data for one session
The localStorage and sessionStorage objects create a key = value pair
Example: key=“Name”, value=“Bob”
They are stored as strings but can be converted after if needed by using JS functions like parseInt() and parseFloat()

Syntax for Web Storage
1)   Storing a Value:
localStorage.setItem("key1", "value1");             object
localStorage["key1"] = "value1";                          array
2)   Getting a Value:
alert(localStorage.getItem("key1"));  
alert(localStorage["key1"]);  
3)   Remove a Value:
removeItem("key1");  
Remove All Values:
localStorage.clear();

No comments:

Post a Comment