On the DOM Storage mechanism of HTML5 (turn)

Source: Internet
Author: User
Tags event listener sessionstorage

When developing WEB applications, developers sometimes need to store data locally. The current browser supports cookie storage, but its size is limited by 4KB. This is for some Ajax
Application is not enough. More storage space requires browser or plugin support, such as Google Gears and
Flash. However, the developer needs to use the corresponding interface by detecting the type of plug-in supported by the current browser. The new DOM Storage is introduced in HTML5.
Mechanism that saves data on the client by using key-value pairs, and provides a greater capacity for storage space. This article will discuss in detail HTML5 support for local storage, and storage event binding and data storage with JSON
Used in conjunction with the discussion. When some older browsers do not support DOM Storage, consider using other techniques such as Dojo to achieve the same functionality. This article will also be a brief introduction to it.

HTML5 is the next generation of HTML standards that begin to attract more and more people's attention. HTML5 's DOM Storage mechanism provides a way for programmers to store information on a local computer and get it when needed. This is similar to a cookie, except that DOM Storage provides a larger capacity for storage space.

Currently, cookies are the most used to save data at the client, but the maximum size of the cookie is 4KB, and the cookie is sent in the past each time a new page is requested. More storage space requires the browser itself or plug-in support, such as UserData, which is used only on Internet Explorer, and Google Gears and Flash, which require additional plugins to install. Now, HTML5 provides a standard interface that allows programmers to easily access stored data. Because key-value pairs are stored on the local computer, the data can be manipulated by JavaScript after the page has been loaded.

DOM Storage Sample application: User Registration

The sample application used in this article is a simple user registration process with three fields: name, age, and address, which we split into two forms, displayed in two pages. With the simplified data model, we mainly describe how to use the DOM Storage feature to handle form spread problems.

DOM Storage two categories

DOM Storage is divided into Sessionstorage and localstorage.

Localstorage objects and Sessionstorage objects are used essentially the same way, and they differ in their scope of action. Sessionstorage is used to store page-related data that cannot be used after a page is closed. The localstorage is persistent and can be used after the page is closed.

DOM Storage Interface

Here is the interface definition for DOM Storage:

Interface Storage {   readonly attribute unsigned long length;   Getter Domstring key (in unsigned long index);   Getter any GetItem (in Domstring key);   Setter creator void SetItem (in Domstring key, in any data);   deleter void RemoveItem (in domstring key);   void Clear ();  };

Length: Returns the number of key-value pairs currently stored in the Storage object.

Key (Index): Returns the first name of the nth key in the list. Index starts from 0.

GetItem (Key): Returns the value corresponding to the specified key.

SetItem (key, value): A key-value pair is stored.

RemoveItem (key): Deletes the specified key-value pair.

Clear (): Removes all key-value pairs from the Storage object.

In general, the most used methods are GetItem and SetItem.

Take Sessionstorage as an example:

Store key-value pairs:

Window.sessionStorage.setItem ("Key1", value1);

To read a value by Key name:

var value1 = Window.sessionStorage.getItem ("Key1");

Determine if the browser supports DOM Storage

To use DOM Storage, first, you need to see if the current browser supports it. Currently more than 8.0 Internet Explorer, Firefox 3.5 or more, Chrome 4.0 or more are supported DOM Storage.

If the browser does not support DOM Storage, you can use other methods as an alternative, and this article uses the Dojox.storage module provided by Dojo to achieve the same functionality.

Listing 1. See if the browser supports DOM Storage
Sessionstorage  if (window.sessionstorage) {     alert ("Support Sessionstorage");  } else{     alert ("Not Sessionstorage");     Do not support sessionstorage     //with dojox.storage to achieve the same function}  //localstorage  if (window.localstorage) {     alert (" Support Localstorage ");  } else{     alert ("Not Localstorage");     Do not support localstorage     //Use Dojox.storage to achieve the same function}

Here are the two forms registered by the user. The first form in Listing 2 has two fields name and age require the user to fill in the content. When you are finished, click the Next button to enter the next page, and the function Savetostorage will be called to save the values of the two fields entered on that page into the Sessionstorage object.

When you return to this page from the next page, use Windows.onload to remove the data from the Sessionstorage when loading the page and display it in the input box for easy user modification.

In addition, assigning values to objects in addition to using the SetItem method, you can also use Window.sessionStorage.key1 = "value1".

Listing 2. First form page
 <script type= "Text/javascript" >//When you return to the first page, you get the value entered by the user from Sessionstorage and display it in the page, which makes it easy to modify the Window.onload = function () {         if (window.sessionstorage) {var name = Window.sessionStorage.getItem ("name");         var = window.sessionStorage.getItem ("Age"); if (Name! = "" | |         name = null) {document.getElementById ("name"). Value = name; } if (age! = "" | |         Age! = null) {document.getElementById ("age"). Value = age;  }}else {//does not support Sessionstorage, implements the same function with Dojo}}; Save data to Sessionstorage object function Savetostorage () {//sessionstorage if (window.sessionstorage) {var         Name = document.getElementById ("name"). Value;         var = document.getElementById ("Age"). Value;         Window.sessionStorage.setItem ("name", name);         Window.sessionStorage.setItem ("Age", age);     Window.location.href= "form2.html"; } else {//does not support Sessionstorage, implements the same function with Dojo}} </script> <form action= "./form2.html" > <input type= "text" name= "name" id= "name" > <input type= "text" Nam E= "Age" id= "age" > <input type= "button" value= "Next" onclick= "Savetostorage ()" ></input> </form>

The second page of Listing 3 has an address field. When the user completes, click the Submit button submission page, at this time the Addstoragevalue function is called, the name and age values saved in Sessionstorage are first assigned to the two hidden fields of the current form, and then submitted to the next page to process the form. Finally, call the RemoveItem function to remove the name and age values.

If the user needs to modify the first page to fill in the content, you can click the Back button to return to the previous page, the user has already filled in the previous page content will appear in the text box.

Listing 3. Second form page
 <script type= "Text/javascript" >//The Hidden property assigned to the form by the data that remains in Sessionstorage function Addstoragevalue () {//sessionsto         Rage if (Window.sessionstorage) {var name = Window.sessionStorage.getItem ("name");         var = window.sessionStorage.getItem ("Age");         document.getElementById ("name"). Value = name;         document.getElementById ("Age"). Value = age;         Window.sessionStorage.removeItem ("name");     Window.sessionStorage.removeItem ("Age"); } else {//does not support Sessionstorage, implements the same function with Dojo}} function Backtopreviousform () {window.location.href= "fo  Rm1.html ";     } </script> <form action= "./form3.php" method= "POST" > <input type= "hidden" name= "name" id= "Name" > <input type= "hidden" name= "age" id= "age" > <input type= "Text" name= "Address" id= "Address" > <inpu T type= "button" value= "Back" onclick= "Backtopreviousform ()" > <input type= "Submit" value= "Submit" onclick= "ADDST Oragevalue () ">&Lt;/input> </form> 
Some points to note in using DOM Storage

Data type saved in the Storage object

When using DOM Storage for local storage, any data format is saved as a string type in the Storage object, so if the saved data is not a string, you need to convert the type yourself when reading. Here we use JSON to serialize the object before storing it.

JSON (JavaScript Object Notation) is a lightweight data interchange format. Easy to read and write, but also easy to machine parse and generate. JSON is now part of the JavaScript standard, and the mainstream browser is perfect for JSON support.

Two related functions are used in this paper

The Json.parse () function converts the JSON object to the original data type.

The Json.stringify () function converts the object to be saved to a JSON object to be saved.

In Listing 4, a Boolean data is first stored in the Storage object, and then taken out, you can see that the Boolean type of data is removed when the string is changed. The next way to save the data, first use the Json.stringify method to serialize the data, and then save to the Storage object, the Json.parse method to deserialize when it is removed, you can see the data read or Boolean type.

In addition, the use of JSON to save a string, through the Chrome Storage tool, you can see the string stored in double quotation marks, the double quotation marks are stored in a string. When you use JSON to represent a simple string, double quotation marks are added around the string. Finally, the page is loaded with the following output:

String1 boolean2 String3

Listing 4. Using JSON to process complex data from DOM Storage
Generates a variable of type Boolean data1  var data1 = new Boolean (true);  No JSON processing data sessionstorage["Key1"] = data1;  if (sessionstorage["key1"] = = "true") {     //data read from Storage object data1 becomes String type    document.write ("string1");  }  //using JSON to process data data1  sessionstorage["Key2"] = json.stringify (data1);  if (Json.parse (sessionstorage["Key2"]) = = True) {     //data read from the Storage object data1, convert the variable to the original Boolean document using JSON    . Write ("boolean2");  }  Generates a variable of type string var data2 = new String ("true");  Using JSON to process data, the Storage object holds "string" sessionstorage["Key3"] = json.stringify (data2);  Data2 = Json.parse (sessionstorage["Key3"]);  if (data2 = = "true") {     //variable is converted back to String type    document.write ("String3");  }

Use the Chrome browser to view the current Sessionstorage and localstorage key-value pairs. You can view key and value by selecting "Tools" to "Developer Tools" to "Resources" to "Local Storage" or "Session Storage" on the toolbar.

Figure 1. Chrome Browser's Storage toolbar

In summary, we can use JSON to transform the data type when loading the page, as in Listing 5, and save the data as a JSON object when you leave the page. In this way, any type of data stored in the Storage can be converted to the original type when it is read.

Listing 5. Using JSON to process complex data from DOM Storage
<script type= "Text/javascript" >  var value;  function Loadvalue () {     value1 = Json.parse (Window.sessionStorage.getItem ("Key1"));  }  function Savevalue () {     Window.sessionStorage.setItem ("key1") = Json.stringify (value1);  }  Window.addeventlistener ("Load", loadvalue. true);  Window.addeventlistener ("Unload", Savevalue. true);  </script>

Space size

HTML5 's recommendation is that each site provides Storage with a space of 5MB, generally enough to store strings. If the data is too large, some browsers such as Chrome will throw quota_exceeded_err exceptions. So while DOM Storage provides a lot more space than a cookie, you need to be aware of the limitations in using it.

Figure 2. Chrome Browser throws an exception

Security

Generally do not store sensitive information on the client, using Localstorage, globalstorage and other information stored on the client is very easy to expose. The data stored in the Storage object should be purged with the clear or RemoveItem method after the data store is complete.

Store Event-driven

If you want to perform some action when the store succeeds or modifies the stored value, you can use the DOM Storage event provided by the interface. You can register an event using the following methods:

Window.addeventlistener ("Storage", handlestorageevent, false);

Store event Interface Definition

Interface Storageevent:event {readonly attribute domstring key;readonly attribute any oldvalue;readonly attribute any NE Wvalue;readonly attribute domstring url;readonly attribute Storage storagearea;void initstorageevent (in domstring Typearg, in-Boolean Canbubblearg, in-Boolean cancelablearg, in Domstring Keyarg, in any oldvaluearg, in any newvaluearg, I n domstring urlarg, in Storage storageareaarg);};

Key: The button that has changed.

OldValue: The value before the key changes.

NewValue: The value after the key has changed.

URL: The URL of the page that triggered the store event.

After registering the storage event in Listing 6, when the value of the Sessionstorage or Localstorage object changes, the Handlestorageevent function is triggered, and the page displays the changed key and the value before and after the change.

Listing 6. Adding storage Events
Display related contents of stored events function handlestorageevent (e) {     document.write ("key" + E.key + "OldValue" + e.oldvalue + "NewValue" + E.newvalue);  }  Add Storage Event Listener Window.addeventlistener ("Storage", handlestorageevent, false);

Back to top of page

Using Dojo to implement pre-user-registered functionality

Dojo is a JavaScript-implemented open-source toolkit that largely masks differences between browsers. The Dojo Extension Library (DOJOX) is a very rich component repository that Dojo provides based on its base libraries, core libraries, and Dijit libraries. The Dojox.storage module used in this paper can save data in local storage and implement the same functions as DOM storage.

Since some older browsers do not support HTML5, we can also use Dojo to implement the functionality previously registered by the user. Dojo's Dojox.storage.Provider interface provides more methods than the HTML5 DOM Storage interface. Here we list a few common methods.

Get (Key, namespace): Returns the value corresponding to the specified key.

Put (key, value, Resultshandler, namespace): Deposit a key-value pair.

Remove (Key, namespace): Deletes the specified key-value pair.

Clear (namespace): Deletes all key-value pairs in the object.

Now make a partial modification to the first form's JavaScript code and introduce the Dojox.storage module to the page. This allows the program to function correctly in browsers that do not support HTML5 by invoking the methods provided by Dojo. Dojo.require ("Dojox.storage") represents the introduction of the Dojox.storage function module. Then, by Dojox.storage.manager.isInitialized () to see if the Dojox.storage.manager has been initialized, and if not, you need to wait for its initialization to complete before storing the operation.

Listing 7. Part of the code for the first form page that has been modified
 <script type= "Text/javascript" > Dojo.require ("Dojox.storage"); When the return to the first page, from the Storage to get the user input before the value and display in the page, easy to modify//here first Dojox.storage.manager initialization if (!).  Dojox.storage.manager.isInitialized ()) {Dojo.connect (Dojox.storage.manager, "loaded", saveandload);  } else{Dojo.connect (Dojo, "Loaded", saveandload);     } function Saveandload () {var name;     var age;         Sessionstorage if (window.sessionstorage) {name = Window.sessionStorage.getItem ("name");         Age = Window.sessionStorage.getItem ("Age"); if (Name! = "" | |         name = null) {document.getElementById ("name"). Value = name; } if (age! = "" | |         Age! = null) {document.getElementById ("age"). Value = age;         }}//dojox.storage Else {name = Dojox.storage.get ("name");         Age = Dojox.storage.get ("Age");         if (typeof name! = "undefined") {document.getElementById ("name"). Value = name; } if (typeof age!)= "undefined") {document.getElementById ("age"). Value = age;     }}}//Save data Function Savetostorage () {var name = document.getElementById ("name"). Value;     var = document.getElementById ("Age"). Value;         Sessionstorage if (window.sessionstorage) {window.sessionStorage.setItem ("name", name);     Window.sessionStorage.setItem ("Age", age);         }//dojox.storage else {dojox.storage.put ("name", name);     Dojox.storage.put ("Age", age);  } window.location.href= "Form2.html"; } </script>
Listing 8. Part of the code for the second form page that has been modified
<script type= "Text/javascript" >  dojo.require ("Dojox.storage");  A hidden property that assigns the data saved in Sessionstorage to the form function Addstoragevalue () {     var name;     var age;     Sessionstorage     if (window.sessionstorage) {         name = Window.sessionStorage.getItem ("name");         Age = Window.sessionStorage.getItem ("Age");         document.getElementById ("name"). Value = name;         document.getElementById ("Age"). Value = age;         Window.sessionStorage.removeItem ("name");         Window.sessionStorage.removeItem ("Age");     } Dojox.storage     else {         name = Dojox.storage.get ("name");         Age = Dojox.storage.get ("Age");         document.getElementById ("name"). Value = name;         document.getElementById ("Age"). Value = age;         Dojox.storage.remove ("name");         Dojox.storage.remove ("Age");     }  }  function Backtopreviousform () {     window.location.href = "form1.html";  }  </script>

Conclusion

The DOM Storage mechanism is introduced in HTML5 to store key-value pairs, designed to provide large-scale, easy-to-use storage capabilities, and programmers can easily access stored data by invoking a standard interface. Currently, many new versions of browsers support DOM Storage functionality. When older browsers do not support the DOM Storage mechanism provided by HTML5, you can consider using Dojo to achieve the same functionality.

Original: http://www.ibm.com/developerworks/cn/web/1107_gaoly_html5storage/

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.