Initial test of localstorage for webstorage

Source: Internet
Author: User

Today, let's take a look at the localstorage feature introduced in HTML5 (later we checked that localstorage should be part of W3C Web storage, rather than HTML5 ),
This feature is also supported in IE8 + and should be supported by other browsers (such as chrome and Firefox will be automatically upgraded to the latest version ).
I also referred to someArticleSuch as dive1_html5 series and
Html5demos series. In short, there are still a lot of resources on the Internet. Let's take a simple test.CodeCome
Description.

First, refer to the tool code, which is introduced in external Js.

 // checks whether the browser supports localstoragevar issupplocallocalstorage = function () {try {return 'localstore' in window & window ['localstore']! = NULL;} catch (e) {return false ;}; // a common method for adding events, however, this write method is more clever. // addevent will initialize the method suitable for the current browser. // you do not need to judge it every time, in addition, the eventhandler call in IE is slightly improved. // make the execution context of eventhandler the element var addevent = (function () {If (document. addeventlistener) {return function (El, type, FN) {If (El & el. nodename | El === window) {el. addeventlistener (type, FN, false);} else if (El & el. length) {for (VAR I = 0; I 
  

The following is the HTML code used for testing. There are two pages A and B in the test. The access method is http: // localhost: 8080/frontend/a.html( B .html). The HTML part is the same.
One input box and one button

 
Save

See the JS Code in page a.html.

If (issupplocallocalstorage () {// clear all stored keys, value values // localstorage. clear (); var datainput = document. getelementbyid ('data'), savebtn = document. getelementbyid ('savebtn '); addevent (savebtn, 'click', function () {// press the button to save the value localstorage in the current input box. setitem ('Storage-event-test', datainput. value) ;}); // listen to the storage event addevent (window, 'store', function (event) for window {// view the event object content // console. dir (event); // output oldvalue and newvalue for observation console. log ('key: % s, old value: % s, new value: % s', event. key, event. oldvalue, event. newvalue) ;}); // stores the number localstorage. setitem ('number', 1 ); // storage object because localstorage is ultimately stored as a string, so if you want to store an object, you can overwrite its tostring method // store it in the desired string format, and then perform corresponding processing. Here we take the JSON format as an example: localstorage. setitem ('obj ', "{'name': 'Andrew', 'job': 'developer '}"); // localstorage for conventional storage. setitem ('string', 'Hello World');} else {// here we can do some downgrade solutions. Of course, we can also provide an unsupported prompt var span = document. createelement ("span"); span. style. color = 'red'; span. innerhtml = 'oops, your browser dones \'t support localstorage yet, :('; document. getelementsbytagname ('body') [0]. appendchild (SPAN );}

next, let's look at the JS Code in B .html, which is basically the same as that in a.html. It's simple to change the storage code in the middle to read.

 If (issupportlocalstorage () {// localstorage. clear (); var datainput = document. getelementbyid ('data'), savebtn = document. getelementbyid ('savebtn '); addevent (savebtn, 'click', function () {localstorage. setitem ('Storage-event-test', datainput. value) ;}); // listen to the storage event addevent (window, 'store', function (event) for window {// view the event object content // console. dir (event); // output oldvalue and newvalue for observation console. log ('key: % s, old value: % s, new value: % s', event. key, event. oldvalue, event. newvalue) ;}); // It is also of the string type. Use parseint to convert it to the console. log (parseint (localstorage. getitem ('number'); // parse the JSON string to use eval and convert it to the console object. dir (eval ('+ localstorage. getitem ('obj ') + "); // read the console normally. log (localstorage. getitem ('string');} else {var span = document. createelement ("span"); span. style. color = 'red'; span. innerhtml = 'oops, your browser dones \'t support localstorage yet, :('; document. getelementsbytagname ('body') [0]. appendchild (SPAN) ;}

I first tested it in firefox5. At the beginning, I encountered a ridiculous problem. I didn't start a local application server to access it (using http: // localhost: 8080 /...), A static page (in the format of file ),
After half a day in firebug, I didn't see the localstorage attribute in the window, and the storage event was not triggered at all. put it in ie9, an error is reported directly in the debug output panel of F12 developer tool. localstorage is null or undefined.
Later, Google found the answer in stackoverflow. localstorage only takes effect through domain name access. It can continue :)

It is normal to store and read data in firefox5, but it seems a bit problematic to trigger the storage event. The storage event of the window is not triggered after setitem is performed on its own page, but the storage event of the window is same as a.htmland B .html at the same time.
Setitem can trigger the storage event of window on page B. Similarly, setitem on page B can trigger the storage event of window on page.
In ie9, the setting value of the page can trigger the storage event of the current page, and the setting value of the current page can trigger the same"Origin"The storage events of other page windows appear more interesting.

The word "Origin" Dev. Opera-webstorage uses origin.
Let me translate origin into a lame "origin". At the end of this article, note the following:
Storage per origin: All storage from the same origin will share the same storage space
AndProtocol + domain name + PortThe same origin can be regarded as the same, and only pages under this origin can share a storage space.
If you are interested, read this article.

Cross-page triggering in Firefox also seems confusing.
My test result is as follows (datainput. value is directly replaced by a string ):

    • In a, setitem ('Storage-event-test', 'aaa')-> console output of B oldvalue:, newvalue: AAAA
    • Setitem ('Storage-event-test', 'bbbbbb')-> A's console output oldvalue:, newvalue: BBBB
    • Setitem ('Storage-event-test', 'cccccc')-> console output of B oldvalue: AAAA, newvalue: CCCC
    • Setitem ('Storage-event-test', 'ddddd')-> A's console output oldvalue: BBBB, newvalue: dddd

As expected, the two pages should share the same storagearea

    • In a, setitem ('Storage-event-test', 'aaa')-> console output of B oldvalue:, newvalue: AAAA
    • Setitem ('Storage-event-test', 'bbbbbb')-> A's console output oldvalue: AAAA, newvalue: BBBB
    • Setitem ('Storage-event-test', 'cccccc')-> console output of B oldvalue: BBBB, newvalue: CCCC
    • Setitem ('Storage-event-test', 'ddddd')-> A's console output oldvalue: CCCC, newvalue: dddd

It seems that the storagearea in localstorage is independent, not for the same"Origin"Shared. However, the part stored on page A can be read normally on page B.
In ie9, the result is what I expected. so at the end, I wondered whether it was a Firefox bug or whether I still had a different understanding of localstorage. If some garden friends knew the reason, I hope to leave a message to guide me,
Thank you.

A problem found in ie9: the same key, whether or not your value is the same as before, will trigger the storage event. In Firefox, no, only when the value is different from the previous one, will be triggered.

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.