Dealing with HTML5 Web Storage

If we want to storage data on the browser like the cookies with html5 we can use local web storage, which allows us to storage more data than the cookies.

There are 2 types of web storage:

Local storage exist always.

Session storage exist until the browser is closed.

How local storage and session is used?

We check if the web storage is available on the browser and then we can set the data.


if(typeof(Storage) !== "undefined") {
//set the data on the localStorage.
 var userObject = JSON.stringify({"name":"John", "lastName":"Doe","Age":"25 years"});
 localStorage.setItem("user", userObject);
} else {
// Web storage are unsupported.
} 

The storage data could be a Json object, we have to set the json object as a string.

To get a storage data item we need to get the data by the key:

var user = JSON.parse(localStorage.getItem("user"));

A storage data item can be removed:

localStorage.removeItem("user");

Use clear method to remove all the items on the web storage.

localStorage.clear();

Same methods as localStorage are used for the sessionStorage the difference is the lifetime.

 

Leave a comment

Create a website or blog at WordPress.com

Up ↑