In front-end development, we often encounter communication between two or more html. We can add parameters in the url, but when the amount of data to be transferred is large, try localStorage in html5.
1) Check whether your browser supports localStorage:
If(Window. localStorage ){
Alert ('Yes! ');
}ElseAlert ('No! ');
2) data is stored in localStorage in the form of key-value pairs. You can simply add an attribute to window. localStorage during use. The following is an example of definition and modification:
// Add a test attribute in window. localStorage and assign the value to test1.
LocalStorage. test = "test1 ";
LocalStorage ["test"] = "test1 ";
LocalStorage. setItem ("test", "test1 ");
// The attribute is worth modifying in the same way as its definition.
// Obtain the property value
Var test = localStorage. test;
Var test = localStorage ["test"];
Var test = localStorage. getItem ("test ");
// Delete attributes
LocalStorage. removeItem ("test"); // clear the property test
LocalStorage. clear (); // clear all attributes
3) The key () and length provided by localStorage can facilitate data traversal of all attributes, for example:
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) localStorage can only store data in the form of key/value pairs. If we want to store a large amount of data, we can try to convert the data into json data, stored as value. For example:
// Set the infomation
Var json = {"name": "echo", "message": "hello localStorage", "id": 1 };
LocalStorage. setItem ("info", json );
// Get the information
Var info = localStorage. getItem ("info ");
Info = eval ("(" + info + ")");
Console. log ("name:" + info. name + "message:" + info. message );
5) If you use html5 canvas for development, you can generate a snapshot of the canvas content and display it in another html file, for example:
// Normal canvas implementation
Var canvas = document. getElementById ("canvas ");
Var url = canvas. toDataURL ("image/png ");
LocalStorage. setItem ("image", url );
// If you use webgl for 3D development, this can be achieved
VarUrl = renderer. domElement. toDataURL ('image/png ', 'name ');
LocalStorage. setItem ("image", url );
6) Finally, the only advantage of localstorage is that the syntax is simple, but the performance is not very good. If you don't need it, try not to use it.