HTML5 and analysis of the Web Storage mechanism (web Storage)

Source: Internet
Author: User
Tags browser cache sessionstorage

Web storage is a data persistence store in the form of Key-value. Web storage are designed to overcome some of the limitations that are caused by cookies. When data needs to be tightly controlled on the client, it is not necessary to continuously send the data back to the server. There are two goals for WEB storage: To provide a path for storing session data, and a mechanism for storing large amounts of data that can be present across sessions.

The original Web Storage specification contained the definition of two objects: Sessionstorage objects and Globalstorage objects. Both objects exist in the supported browsers as Window object properties, and browsers that support the Sessionstorage and Globalstorage properties are: Firefox 3.5+, Opera 10.5+, Chrome 4+, and IE 8+. Firefox 2 and Firefox 3 based on the content of the early specification of the implementation of the Web Storage, at that time only implemented the Globalstorage, did not implement Localstorage.


1. Storage type


The storage type provides the largest storage space (browser-dependent) to store name-value pairs. Storage instances are similar to other objects, there are several methods.

Clear (): Delete all values, not supported in Firefox.

Gititem (name): Gets the corresponding value based on the specified name (name).

Key (index): Gets the name of the value at the index position (name).

RemoveItem (name): Deletes the name-value pair specified by name.

SetItem (name, value): sets a corresponding value for the specified name.


where GetItem (), RemoveItem (name), and SetItem (name, value) methods can be called directly or indirectly through storage objects. Because each item is stored as an attribute on the object, you can read the value by accessing the property through either point syntax or square bracket syntax. Settings, or delete by using the delete operator. However, it is best to use methods to make calls instead of properties to access the data, so as not to rewrite the error caused by the object.

You can also use the Length property to determine how many name-value pairs are placed in the storage object. However, you cannot determine the size of all the data in the object. The storage type can only store strings. Non-string data is converted to a string before it is stored.


2. Globalstorage Object


The Globalstorage object was implemented as early as Firefox 2. This object exists for the purpose of storing data across sessions, but with specific access restrictions. To use the Globalstorage object, you first specify what is and can access the data. You can use a property by using the square brackets tag. Small examples are as follows


  JavaScript code


Save Data globalstorage["www.leemagnum.com"].name = "leemagnum";//Get data var name = globalstorage["Www.leemagnum.com"]. Name;alert (name)//leemagnum


The above example must be under the Www.leemagnum.com domain name to access, and only support Firefox 3.6+. Here, you are accessing storage space for "www.leemagnum.com". The Globalstorage object is not an instance of storage, and the specific globalstorage["www.leemagnum.com" is. This storage space is accessible to "www.leemagnum.com" and all of its subdomains. Some browsers allow for broader access restrictions, such as restricting only the top-level domain name or allowing global access, as shown in the following example.


  JavaScript code


globalstorage["leemagnum.com"].name = "leemagnum1"; globalstorage["com"].name = "leemagnum2"; globalstorage[""].name = "LEEMAGNUM3";


The above is not supported, no matter how access, is not supported. The above method is not supported because it involves security issues. Be sure to make a domain name when using Globalstorage objects.

Access to the Globalstorage object space is limited by the domain name, protocol, and Port of the page on which the request originated. For example, using the HTTPS protocol to store data in "leemagnum.com", the "leemagnum.com" page accessed via HTTP cannot access this data. Pages accessed through port 80 cannot share data with pages accessed by different ports on the same protocol as the unified domain name. Each property of the Globalstorage object is an instance of storage. How to use it, just look at the following small example.


  JavaScript code


globalstorage["www.leemagnum.com"].name = "leemagnum"; globalstorage["www.leemagnum.com"].age = "12";// Delete Data globalstorage["www.leemagnum.com"].removeitem ("name");//Get data var age = globalstorage["www.leemagnum.com"]. GetItem ("Age");


If you implement a domain name that cannot be determined, you can use Location.host as the property name to be more secure. Small examples are as follows


  JavaScript code


Save Data Globalstorage[location.host].name = "leemagnum";//Get Data var = globalstorage[location.host].getitem ("Age");


If you do not use RemoveItem () or delete delete, or if the user does not clear the browser cache, the data stored in the Globalstorage property remains on disk. This makes globalstorage ideal for storing documents on the client or for long-term saving of user preferences.


3. Localstorage Object


The Localstorage object replaces the Globalstorage object in the HTML5 specification. Unlike the Globalstorage object, the Localstorage object cannot specify any access rules. Localstorage access rules are set up beforehand. To access the same Localstorage object, the page must be from the same domain name (the subdomain is invalid) and must use the same protocol on the same port. This is equivalent to Globalstorage[location.host].

Because the Localstorage object is an instance of storage, you can use it as you would with a Sessionstorage object. A small example is as follows.


  JavaScript code


Use the method to store data Localstorage.setitem ("name", "Leemagnum");//use attribute to store data Localstorage.age = "12";//Use method to read data var name = Localstorage.getitem ("name");//use attribute to read data var = localstorage.age;


The same rules are followed for the data stored in the Localstorage object and the data stored in the Globalstorage object. Data is retained to be deleted via JavaScript or the user clears the browser cache. To be compatible with browsers that support only globalstorage, you can use the function.


  JavaScript code


function Getlocalstorage () {if (typeof Localstorage = = "Object") {return localstorage;} else if (typeof globalstorage = = "Object") {return globalstorage[location.host];} Else{alert ("Your browser does not support premium storage")}}


Then, call this function as follows so that you can read and write the data normally.


  JavaScript code


var storage = Getlocalstorage ();


Once you have determined which storage object to use, you can use the same access rules to manipulate the data in all browsers that support Web storage.


4. Sessionstorage Object


Sessionstorage objects like session cookies are kept only until the browser is closed. Data stored in Sessionstorage can exist across page refreshes, and colleagues will be available if browser support, browser crashes and restarts (Firefox and WebKit are supported, IE is not supported).

Because the Sessionstorage object is bound to a server dialog, it is not available when the file is running locally. The data stored in the Sessionstorage can only be accessed by the page that originally stored the data for the object, so there are restrictions on the application of multiple pages.

Since the Sessionstorage object is actually an instance of storage, use SetItem () or set a new property directly to store the data. The following is a small example of stored data


  Javascript


Use the method to save data sessionstorage.setitem ("name", "Leemagnun");//use attribute to store data Sessionstorage.age = "12";


Different browsers write data differently. Firefox and WebKit implement synchronous writes, so the data added to the storage space is immediately submitted. The implementation of IE is to write data asynchronously, so there may be some delay in setting up the data and writing the data to disk directly. For a small amount of data, this difference can be ignored. For a lot of data, ie will be faster than other browsers.

You can force data to be written to disk in IE8: Use the Begin () method before setting up the data, and call the Commit () method after all settings are complete. Small examples are as follows


  JavaScript code


Only applicable to Ie8sessionstorage.begin (); seesionstorage.name = "Leemagnum"; sessionstorage.age = "n"; Sessionstorage.commit ( );


This code ensures that the value of name and book is written to the disk immediately after the call to commit (). The Begin () method is called to ensure that no additional disk writes occur when this code executes. This process is not necessary for a small amount of data, but for large amounts of data. This method must be considered.

When there is data in the Sessionstorage object, the data can be obtained using the GetItem () method or by directly accessing the property name. Small examples are as follows


  JavaScript code


Use the method to save data sessionstorage.setitem ("name", "Leemagnun");//use attribute to store data Sessionstorage.age = "12";


The above code facilitates the sessionstorage of the name-value pairs in this way: First, the key () method to get the name at the specified position, and then through the GetItem () method to find the corresponding name of the value. The value in Sessionstorage can be obtained by using the For loop above as well as the for-in loop. Small examples are as follows


  JavaScript code


Use the method to save data sessionstorage.setitem ("name", "Leemagnun");//use attribute to store data Sessionstorage.age = "n"; var = sKey = ""; for (i= 0; i<sessionstorage.length; i++) {SKey = Sessionstorage.key (i); value = Sessionstorage.getitem (SKey);} Alert (SKey + "=" + value)//name = Leemagnum


Each time the loop is passed, the key is set to the next name in the Sessionstorage, and no built-in method or length property is returned at this time.

To remove data from a Sessionstorage object, you can use the delete operator to delete an object property, or you can call the RemoveItem () method. A small example is as follows.


  JavaScript code


Use the For-in method var value = ""; for (var i in sessionstorage) {value = Sessionstorage.getitem (i);} Alert (i + "=" + value)//name = Leemagnum


However, the delete operator may fail in WebKit, so it is appropriate to use the RemoveItem () method. The Sessionstorage object should be used primarily for storage of small pieces of data that are only for sessions. If you need to store data across sessions, then the Globalstorage object or Localstorage object is more appropriate.


5. Storage Events


Any modifications to the storage object will trigger the storage event on the document. The storage event occurs when you save data through attributes or the SetItem () method, when you delete data by using the delete operator or the RemoveItem () method, or when you call the clear () method. The properties of the event object for storage events are as follows:


Domain: The name of the storage space that has changed.

key: Set or delete the keys name

newvalue: If the setting value is the new value, or null if the key is deleted

oldValue: The value before the key is changed.


Of these four events, IE8 and Firefox only implemented the domain event. The old version of WebKit also does not support the storage event. The storage event is monitored in the following way


  JavaScript code


Document.addeventlistener (' Storage ', function (event) {alert ("The domain name of the changed storage space is:  " + Event.domain);}, False);


The storage event is triggered regardless of whether the Sessionstorage object, the Globalstorage object, or the Localstorage object are manipulated.


  6. Restrictions


Web Storage is similar to other client data storage scenarios, and Web storage also has limitations. These restrictions vary by browser. Most are limited to the size of the storage space in terms of each source (protocol, domain, and port). This means that each source has a fixed-size space for storing its own data.

For Localstorage objects, most desktop browsers set a limit of 5MB per source. Chrome and Safari have a 2.5MB limit on each source. The iOS version of Safari and Android WebKit is also limited to 2.5MB.

Restrictions on Sessionstorage objects are also different for browsers. Some browsers have no restrictions on the size of Sessionstorage objects. But Safari, Chrome, iOS Safari and Android WebKit all have a limit of 2.5MB. ie8+ and Opera Limit the Sessionstorage object to 5MB.


7. Support situation


Web storage support in the browser: ie8+, Firefox 3.5+, Chrome 4.0+, Opera 10.5+, Android version WebKit and iOS version of Safari.



8, a comprehensive small example


  HTML code




  JavaScript code


Window.onload = function () {var oadd = document.getElementById ("Add"), Ofind = document.getElementById ("Find"), Odelete = document.getElementById ("delete");//save Data Oadd.onclick = function () {var mobilephone = document.getElementById (" Mobilephone "). Value; var user_name = document.getElementById ("user_name"). Value; Localstorage.setitem (Mobilephone,user_name); }//Find data Ofind.onclick = function () {var search_phone = document.getElementById ("Search_phone"). value; var name = Localsto Rage.getitem (Search_phone); var find_result = document.getElementById ("Find_result"); find_result.innerhtml = Search_phone + "Of the Machine Master is:" + name; }//clears all data Odelete.onclick = function () {localstorage.clear (); Loadall ()};//extracts all objects stored in localstorage and presents them to the interface Loadall () function Loadall () {var list = document.getElementById ("list"), if (localstorage.length>0) {var result = " <table border= ' 1 ' > "; Result + = "<tr><td> name </td><td> mobile number </td></tr>"; for (Var i=0;i<localstorage.length;i++) {varMobilephone = Localstorage.key (i); var name = Localstorage.getitem (mobilephone); Result + = "<tr><td>" +name+ "</td><td>" +mobilephone+ "</td></tr>"; } result + = "</table>"; list.innerhtml = result; }else{list.innerhtml = "The current data is empty, quickly start to join the contact bar";}} };


HTML5 actual combat and analysis of the Web Storage mechanism (web Storage) for everyone to introduce. Web storage are stored for data persistence. Web storage are designed to overcome some of the limitations that are caused by cookies. The generation of WEB storage is a revolution in data storage. Learn more about HTML5 at Dream Dragon Station.






HTML5 and analysis of the Web Storage mechanism (web Storage)

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.