The use of HTML5 localStorage

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

In the development of the front end, we often encounter in two or between multiple HTML communication, we can add the parameters in the URL, but when it comes to transfer large amounts of data are more, might as well try HTML5 localStorage.  

1) Check your browser does not support localStorage:



} else alert('NO!');

2) The data are in the form of key / value store in localStorage, add an attribute in the window.localStorage when using it, define and modify the example below:

//Add a test attribute in the window.localStorage, and assign the three means of realization of test1

localStorage.test = “test1”,

localStorage[“test”] = “test1”,


//Attribute is modified with its definition.

//Get the property value

var test = localStorage.test;

var test = localStorage[“test”];

var test = localStorage.getItem(“test”);

//Attribute deletion

localStorage.removeItem(“test”);//Scavenging properties test

localStorage.clear();//Remove all attributes

3) LocalStorage key (length) and can realize all the attribute data traversal convenient, cases:

var storage = window.localStorage;

var key = “”;

for(var i = 0;I <storage.length;i++){

key = storage.key(i);

console.log(key + “ : ” + localStorage.getItem(key));


4)The localStorage can only store the key/value key on the form of data, if we want to store a large amount of data that, try to put these data into JSON data, stored in a value value. Such as:

//set the infomation

var json = {“name”:”echo”,”message”:”hello localStorage”,”id”:1};


//get the information

var info = localStorage.getItem(“info”);

info = eval(“(” + info + ”)”);

console.log(“name:”” message:”+info.message);

5)If you use HTML5 canvas development, you can put the contents of this canvas generates a snapshot in another HTML display, such as:

//The common canvas implementation

var canvas = document.getElementById(“canvas”);

var url = canvas.toDataURL(“image/png”);


//If you use webgl 3D development, can be realized

var url = renderer.domElement.toDataURL('image/png','name');


6)Finally, localstorage only advantage is simple, but the performance is not very good, we don't need to use them as far as possible without.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Lori at December 18, 2013 - 5:26 PM