HTML5 local storage, html5localstorage

Source: Internet
Author: User
Tags string to json

HTML5 local storage, html5localstorage

Speaking of local storage, this is a tough task to go To the HTML5 step, as shown in the previous history:

 

The earliest Cookies are naturally known to all. The problem is that they are too small and approximately 4 kb. IE6 only supports 20 cookies for each domain name, which is too small. The advantage is that everyone supports it, and the support is quite good. A long time ago, users who disabled cookies gradually did not exist, as if they had previously disabled javascript.

UserData is Internet Explorer. Flash is the most commonly used, and the space is 25 times that of cookies, which is basically enough. After that, Google launched Gears. Although there are no restrictions, it is uncomfortable to install additional plug-ins (no specific research has been conducted ). By HTML5, these are all unified. The official suggestion is that each website is 5 MB. If it is very large, some strings will be saved, which is enough. The strange thing is that all supported browsers currently use 5 MB. Although some browsers can be set for users, for web page makers, it is appropriate to consider the current situation in 5 MB.

 

For example, IE was supported in 8.0, which is quite unexpected. However, during IE and Firefox testing, you must upload the file to the server (or localhost) and directly open the local HTML file.

First, check whether the browser supports local storage. In HTML5, local storage is a window attribute, including localStorage and sessionStorage. The difference between the two can be clearly identified by name. The former is always local, the latter is only accompanied by the session. Once the window is closed, it will be gone. The two are used in the same way. Here, localStorage is used as an example.

1 if(window.localStorage){
2 alert('This browser supports localStorage');
3 }else{
4 alert('This browser does NOT support localStorage');
5 }

You can directly add an attribute to window. localStorage, such as window. localStorage. a or window. localStorage ["a"]. The method for reading, writing, and deleting data is simple. It exists as a key-value pair, as shown below:

1 localStorage. a = 3; // set a to "3"
2 localStorage ["a"] = "sfsf"; // set a to "sfsf", overwrite the above value
3 localStorage. setItem ("B", "isaac"); // Set B to "isaac"
4 var a1 = localStorage ["a"]; // obtain the value of
5 var a2 = localStorage. a; // obtain the value of
6 var B = localStorage. getItem ("B"); // obtain the value of B
7 localStorage. removeItem ("c"); // clear the value of c

Here, we recommend that you use getItem () and setItem () to clear key-value pairs and use removeItem (). To clear all key-value pairs at a time, use clear (). In addition, HTML5 provides a key () method, which can be used when you do not know which key values are available, as follows:

1 var storage = window. localStorage;
2 function showStorage (){
3 for (var I = 0; I <storage. length; I ++ ){
4 // key (I) to obtain the corresponding key, and then use the getItem () method to obtain the corresponding value
5 document. write (storage. key (I) + ":" + storage. getItem (storage. key (I) + "<br> ");
6}
7}

Write a simple counter that uses local storage:

1 var storage = window. localStorage;
2 if (! Storage. getItem ("pageLoadCount") storage. setItem ("pageLoadCount", 0 );
3 storage. pageLoadCount = parseInt (storage. getItem ("pageLoadCount") + 1; // format conversion required
4 document. getElementByIdx_x ("count"). innerHTML = storage. pageLoadCount;
5 showStorage ();

As shown in:

Note that the local storage of HTML5 can only store strings, and will be automatically converted to strings during storage of any format. Therefore, you need to convert the data type during reading. This is why parseInt must be used in the previous code.

In addition, sometimes when setItem () is set on the iPhone/iPad, a strange QUOTA_EXCEEDED_ERR error occurs. In this case, removeItem () is OK before setItem.

HTML5 local storage also provides a storage event that can be used to listen for changes to key-value pairs as follows:

1 if(window.addEventListener){
2 window.addEventListener("storage",handle_storage,false);
3 }else if(window.attachEvent){
4 window.attachEvent("onstorage",handle_storage);
5 }
6 function handle_storage(e){
7 if(!e){e=window.event;}
8 //showStorage();
9 }

The event variable e is a StorageEvent object and provides some practical attributes to observe the changes of key-value pairs, as shown in the following table:

Property Type Description
Key String The named key that was added, removed, or moddified
OldValue Any The previous value (now overwritten), or null if a new item was added
NewValue Any The new value, or null if an item was added
Url/uri String The page that called the method that triggered this change

Add two key-value pairs a and B and add a button. Set a fixed value for a. When you click the button, modify the value of B:

1 <body>
2 <p> You have viewed this page <span id = "count"> 0 </span> time (s). </p>
3 <p> <input type = "button" value = "changeStorage" onClick = "changeS ()"/> </p>
4 <script>
5 var storage = window. localStorage;
6 if (! Storage. getItem ("pageLoadCount") storage. setItem ("pageLoadCount", 0 );
7 storage. pageLoadCount = parseInt (storage. getItem ("pageLoadCount") + 1; // format conversion required
8 document. getElementByIdx_x ("count"). innerHTML = storage. pageLoadCount;
9 showStorage ();
10 if (window. addEventListener ){
11 window. addEventListener ("storage", handle_storage, false );
12} elseif (window. attachEvent ){
13 window. attachEvent ("onstorage", handle_storage );
14}
15 function handle_storage (e ){
16 if (! E) {e = window. event ;}
17 showObject (e );
18}
19 function showObject (obj ){
20 // recursively display the object
21 if (! Obj) {return ;}
22 for (var I in obj ){
23 if (typeof (obj [I])! = "Object" | obj [I] = null ){
24 document. write (I + ":" + obj [I] + "<br/> ");
25} else {
26 document. write (I + ": object" + "<br/> ");
27}
28}
29}
30 storage. setItem ("a", 5 );
31 function changeS (){
32 // modify a key value to test the storage event
33 if (! Storage. getItem ("B") {storage. setItem ("B", 0 );}
34 storage. setItem ('B', parseInt (storage. getItem ('B') + 1 );
35}
36 function showStorage (){
37 // display the key-value pairs in localStorage cyclically
38 for (var I = 0; I <storage. length; I ++ ){
39 // key (I) to obtain the corresponding key, and then use the getItem () method to obtain the corresponding value
40 document. write (storage. key (I) + ":" + storage. getItem (storage. key (I) + "<br> ");
41}
42}
43 </script>
44 </body>

 

The test shows that the browser currently does not support this function very well. It only supports iPad and Firefox. In addition, Firefox does not support these attributes at all. The iPad supports very well. It uses e. uri (not e. url) and Safari on the desktop.

Currently, browsers have good developer debugging functions. The following are debugging tools for Chrome and Firefox to view LocalStorage:

In addition, javascript currently uses a lot of json format. If you want to store it locally, you can directly call JSON. stringify () to convert it into a string. After reading the data, call JSON. parse () to convert the string to json format, as shown below:

1 var details = {author:"isaac","description":"fresheggs","rating":100};
2 storage.setItem("details",JSON.stringify(details));
3 details = JSON.parse(storage.getItem("details"));

JSON objects are basically supported in browsers that support localStorage. It should be noted that IE8 supports JSON, but if the following compatible mode code is added, it cannot be switched to IE7 mode (localStorage is still supported at this time, although the window is displayed. localStorage is [object] instead of the previous [object Storage], but it is found that getItem (), setItem () and so on can be used ).

<meta content="IE=7" http-equiv="X-UA-Compatible"/>

(Reprinted please indicate the source: http://blog.sina.com.cn/s/blog_4515673f0100mm6m.html)

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.