HTML5 analysis of the real-combat Web Storage mechanism (web Storage)

Source: Internet
Author: User
Tags sessions browser cache sessionstorage

Web Storage It is the form of key-value in persistent data storage. Web storage to overcome some of the limitations caused by cookie. When data requires strict control of the client on time, there is no need to continually send back to the data server.

Web Storage has two purposes: to provide a path for storing session data, and a mechanism for storing large amounts of data that can exist across sessions.

The original Web Storage specification included the definition of two objects: Sessionstorage objects and Globalstorage objects. Both objects exist in a supported browser in the form of Window object properties. 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 implemented Web Storage based on the content section of the early specification. The globalstorage was only realized at that time. No implementation of 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, and there are several ways to do this.

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

Gititem (name): Gets the corresponding value according to 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.


The 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, it is possible to read the value by using the point syntax or the square bracket syntax to access the property.

Settings, or delete by using the delete operator. Simply, it is better to use the call instead of the property to access the data, so as not to rewrite the error caused by the object.

You can also use the Length property to infer how many name-value pairs are placed in the storage object. However, you cannot infer 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 has specific access restrictions. To use the Globalstorage object, you first specify what is and can access the data.

The ability to use attributes through the square brackets tag. Sample examples such as the following


  JavaScript code


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


The example above must be available below the www.leemagnum.com domain name and only support Firefox 3.6+. Here, the access is for "www.leemagnum.com" storage space. The Globalstorage object is not an instance of storage, and the detailed globalstorage["www.leemagnum.com" is. This storage space is available for "www.leemagnum.com" and all subdomains. Some browsers agree to broader access restrictions, such as restricting or agreeing to global access based on top-level domain names, such as the following.


  JavaScript code


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


The above is not supported, no matter how the interview. are not supported. The above method is not supported because of the security concerns involved.

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 that originated the request.

For example, using the HTTPS protocol to store data in "leemagnum.com", the "leemagnum.com" page that is visited by HTTP is not able to access this data. The 80port access page does not share data with the same agreement as the unified domain name of the page to which the port is being interviewed.

Each property of a Globalstorage object is an instance of storage. How to use it, see the following sample


  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");


Suppose you implement a domain name that cannot be determined. It is more secure to use Location.host as the property name.

Sample examples such as the following


  JavaScript code


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


Suppose you do not use RemoveItem () or delete delete, or the user does not clear the browser cache. The data stored in the Globalstorage property remains on disk.

This makes globalstorage useful for storing documents in 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 be specified regardless of the access rules.

Localstorage access rules are set in advance.

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. So you can use it just like you would with a Sessionstorage object. Sample examples are as follows.


  JavaScript code


Usage stores Data localstorage.setitem ("name", "Leemagnum");//use attribute to store data Localstorage.age = "12";//usage read data var name = Localstorage.getitem ("name");//use attribute to read data var = localstorage.age;


The data stored in the Localstorage object is the same as the data stored in the Globalstorage object. All follow the same rules. 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 functions.


  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, and 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 assume browser support. Browsers are still available after crashing and restarting (Firefox and WebKit are supported.) IE not supported).

Because the Sessionstorage object is bound to a server dialog, it is not available when the file is executed locally.

The data stored in Sessionstorage can only be visited by the page that originally stored the data for the object. Therefore, there are restrictions on the application of multiple pages.

Because 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 sample of the number of stored data


  Javascript


Usage 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 large amounts of data. IE will be faster than other browsers.

In IE8, you can force data to be written to disk: Use the Begin () method before setting up the data. and the Commit () method is called after all setup is complete. Sample examples such as the following


  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 disk immediately after the call to commit ().

The Begin () method is called to ensure that no additional disk writes occur while this code is running.

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. Data can be obtained using the GetItem () method or by direct access to the property name. Sample examples such as the following


  JavaScript code


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


The above code facilitates the flow of name-value pairs in Sessionstorage: first get the name at the specified position through the key () method. The value of the corresponding name is then identified by the GetItem () method. By the above for loop can get the value of Sessionstorage can also be used for-in loop. Sample examples such as the following


  JavaScript code


Usage 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. No built-in methods or length properties are 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. Sample examples are 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


But. The delete operator may fail in WebKit, so it is more 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, Globalstorage objects or localstorage objects are better suited.


5. Storage Events


No matter what changes are made to the storage object, the storage event will be triggered on the document. Save the data through the properties or SetItem () method, using the delete operator or the RemoveItem () method to delete the data. Or when the clear () method is called, the storage event occurs.

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: Assuming that the setting value is the new value, assuming that the DELETE key is null

oldValue: The value before the key is changed.


In these four events. IE8 and Firefox have only implemented domain events.

The old version number of WebKit also does not support the storage event. Storage event monitoring methods such as the following


  JavaScript code


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


Whether you manipulate Sessionstorage objects, globalstorage objects, or Localstorage objects, the storage event is triggered, but not differentiated.


  6. Restrictions


The Web storage is similar to other client data storage scenarios. WEB storage have the same 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. Comprehensive sample


  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 display 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 = "Now that the data is empty, quickly start adding Contacts";}} };


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.

Many other relevant knowledge about HTML5 in the Dream Dragon Station.






Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

HTML5 analysis of the real-combat 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.