HTML5 practice and analysis-Web Storage)

Source: Internet
Author: User
Tags sessionstorage

HTML5 practice and analysis-Web Storage)

Web Storage stores data persistence in the form of Key-Value. Web Storage is generated to overcome some restrictions brought by cookies. When the data needs to be strictly controlled on the client, you do not need to send the data back to the server continuously. There are two goals for Web Storage: to provide a path to store session data, and to provide a mechanism to store a large amount of data that can exist across sessions.

The original Web Storage specification defined two objects: sessionStorage object and globalStorage object. These two objects exist in the form of window object attributes in supported browsers. browsers that support sessionStorage and globalStorage attributes include: firefox 3.5 +, Opera 10.5 +, Chrome 4 +, and IE 8 +. Among them, Firefox 2 and Firefox 3 Implemented Web Storage Based on the Content part of earlier specifications. At that time, only globalStorage was implemented and localStorage was not implemented.


1. Storage Type


The Storage type provides the largest Storage space (different from the browser) to store name-value pairs. The Storage instance is similar to other objects. There are several methods below.

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

GitItem(Name): obtains the corresponding value based on the specified name.

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

RemoveItem(Name): delete the name-Value Pair specified by name.

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


The getItem (), removeItem (name), and setItem (name, value) methods can be called directly or indirectly through the Storage object. Because each item is stored on this object as an attribute, you can access the attribute to read the value through the dot syntax or square brackets syntax. The settings are the same, or you can delete them using the delete operator. However, it is best to use methods instead of attributes to access data to avoid errors caused by rewriting objects.

You can also use the length attribute to determine how many pairs are stored in the storage object. However, the size of all data in the object cannot be determined. The Storage type can only store strings. Non-string data is converted into strings before being stored.


2. globalStorage object


As early as Firefox 2, globalStorage objects were implemented. This object is generated to store data across sessions, but has specific access restrictions. To use a globalStorage object, you must first specify which data can be accessed. You can use square brackets to mark attributes. Example


  JavaScript code


// Save the data globalStorage ["www.leemagnum.com"]. name = "leemagnum"; // obtain the data var name = globalStorage ["www.leemagnum.com"]. name; alert (name) // leemagnum


The above example can only be accessed under the domain name www.leemagnum.com, and only Firefox 3.6 + is supported. Here, we access the bucket "www.leemagnum.com. The globalStorage object is not a Storage instance, but the specific globalStorage ["www.leemagnum.com"] is. This bucket is accessible to "www.leemagnum.com" and all its subdomains. Some browsers allow more broad access restrictions. For example, you can only restrict access based on top-level domain names or allow global access. The following is a small example.


  JavaScript code


globalStorage["leemagnum.com"].name = "leemagnum1";globalStorage["com"].name = "leemagnum2";globalStorage[""].name = "leemagnum3";


This is not supported. No matter how you access it, it is not supported. The preceding method is not supported because it involves security issues. When using a globalStorage object, you must specify a domain name.

Access to the globalStorage object space is restricted based on the domain name, protocol, and port of the page that initiates the request. For example, if you use HTTPS to store data in "leemagnum.com", the "leemagnum.com" page accessed through HTTP cannot access the data. The page accessed through port 80 cannot share data with the page accessed through the same protocol as the unified domain name. Each attribute of the globalStorage object is a Storage instance. Let's take a 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"); // obtain the data var age = globalStorage ["www.leemagnum.com"]. getItem ("age ");


If you cannot determine the domain name, you can use location. host as the attribute name for security. Example


  JavaScript code


// Save the data globalStorage [location. host]. name = "leemagnum"; // obtain the data var age = globalStorage [location. host]. getItem ("age ");


If removeItem () or delete is not used, or the browser cache is not cleared, the data stored in the globalStorage attribute will remain on the disk. This makes globalStorage very suitable for storing documents on the client or saving user preference settings for a long time.


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. The localStorage access rules are set in advance. To access the same localStorage object, the page must come from the same domain name (the sub-domain name is invalid) and use the same protocol on the same port. This is equivalent to globalStorage [location. host].

Because the localStorage object is a Storage instance, you can use it like using the sessionStorage object. The following is a small example.


  JavaScript code


// Use localStorage to store data. setItem ("name", "leemagnum"); // use the property to store localStorage. age = "12"; // read data using var name = localStorage. getItem ("name"); // use the attribute to read data var age = localStorage. age;


The data stored in the localStorage object follows the same rules as the data stored in the globalStorage object. The data is retained to JavaScript deletion or the browser cache is cleared by the user. To be compatible with browsers that only support globalStorage, you can use the following 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 advanced storage ")}}


Then, call this function as follows to read and write data normally.


  JavaScript code


var storage = getLocalStorage();


After determining which Storage object to use, you can use the same access rule to operate data in all browsers that support Web Storage.


4. sessionStorage object


SessionStorage objects like session cookies are only kept in the browser closed. Data stored in sessionStorage can be refreshed across pages. If the browser is supported by colleagues, the browser will remain available after crash and restart (both Firefox and Webkit are supported, and IE is not supported ).

Because the sessionStorage object is bound to a server conversation, it is unavailable when the file is running locally. Data stored in sessionStorage can only be accessed through the page where data is originally stored for the object, so there are restrictions on multiple page applications.

Because the sessionStorage object is actually an instance of Storage, you can use setItem () or directly set a new attribute to store data. Below is a small example of data storage


  JavaScript


// Use methods to store data sessionStorage. setItem ("name", "leemagnun"); // use properties to store data sessionStorage. age = "12 ";


Different browsers write data differently. Firefox and Webkit implement synchronous writing, so the data added to the bucket is submitted immediately. The implementation of IE is to write data asynchronously. Therefore, there may be some latency when setting data and writing data to the disk. This difference can be ignored for a small amount of data. For a large amount of data, IE will be faster than other browsers.

You can forcibly write data to the disk in IE8: Use the begin () method before setting data, and call the commit () method after all the settings are complete. Example


  JavaScript code


// Only applicable to IE8sessionStorage. begin (); seesionStorage. name = "leemagnum"; sessionStorage. age = "12"; sessionStorage. commit ();


This Code ensures that the value of name and book is immediately written to the disk after calling commit. The begin () method is called to ensure that no other disk write operations will occur during code execution. This process is not necessary for a small amount of data, but for a large amount of data. This method must be considered.

When the sessionStorage object contains data, you can use the getItem () method or directly access the attribute name to obtain data. Example


  JavaScript code


// Use methods to store data sessionStorage. setItem ("name", "leemagnun"); // use properties to store data sessionStorage. age = "12 ";


The code above facilitates the process of name-value pairs in sessionStorage: first, get the name at the specified location through the key () method, and then find the value corresponding to this name through the getItem () method. The preceding for loop can be used to obtain the values in sessionStorage or the for-in loop. Example


  JavaScript code


// Use the method to store the number of data sessionStorage. setItem ("name", "leemagnun"); // use attributes to store data sessionStorage. age = "12"; var value = sKey = ""; for (I = 0; I
 
  
// 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 in Webkit may fail, so it is appropriate to use the removeItem () method. SessionStorage objects should be mainly used for the storage of session-specific small data segments. If you need to store data across sessions, the globalStorage object or localStorage object is more suitable.


5. Storage events


Any modification to the Storage object will trigger the storage event on the document. Data is saved using the attribute or setItem () method. When the delete operator or removeItem () method is used to delete data, or the clear () method is called, a storage event occurs. The attributes of the Storage event object include the following:


Domain: The domain name of the bucket that has changed.

Key: Key name set or deleted

NewValue: If it is set, it is a new value; if it is a delete key, it is null

OldValue: The value before the key is changed.


Among the four events, IE8 and Firefox only implement domain events. Earlier versions of Webkit do not support storage events. The storage event listening method is as follows:


  JavaScript code


Document. addEventListener ('store', function (event) {alert ("the domain Name of the bucket in change is:" + event. domain) ;}, false );


Operations on sessionStorage objects, globalStorage objects, and localStorage objects will trigger storage events, but they are not differentiated.


  6. Restrictions


Similar to other client data Storage solutions, Web Storage also has restrictions. These restrictions vary with browsers. Most of them use the unit of each source (protocol, domain, and port) to limit the size of the bucket. That is to say, each source has a fixed size of space to store its own data.

For localStorage objects, most desktop browsers set a limit of 5 MB for each source. Chrome and Safari impose a limit of 2.5 MB on each source. The limits for Safari and Webkit for iOS and Android are 2.5 MB.

The limitations on sessionStorage objects vary with browsers. Some browsers have no limit on the sessionStorage object size. However, Safari, Chrome, iOS Safari, and Android Webkit have limits, both of which are 2.5 MB. IE8 + and Opera have a limit of 5 MB for sessionStorage objects.


7. Support


Web Storage support in browsers: IE8 +, Firefox 3.5 +, Chrome 4.0 +, Opera 10.5 +, Android Webkit, and iOS Safari.



8. small examples


  HTML code


 Name:  
Mobile phone:
Enter the mobile phone number:





  JavaScript code


Window. onload = function () {var oAdd = document. getElementById ("add"), oFind = document. getElementById ("find"), oDelete = document. getElementById ("delete"); // Save the data oAdd. onclick = function () {var mobilephone = document. getElementById ("mobilephone "). value; var user_name = document. getElementById ("user_name "). value; localStorage. setItem (mobilephone, user_name);} // search for data oFind. onclick = function () {var search_phone = document. getElementById ("search_phone "). value; var name = localStorage. getItem (search_phone); var find_result = document. getElementById ("find_result"); the host of find_result.innerHTML = search_phone + "is:" + name ;}// clear all data oDelete. onclick = function () {localStorage. clear (); loadAll ()}; // extract all objects stored in localStorage and display them to loadAll () function loadAll () {var list = document. getElementById ("list"); if (localStorage. length> 0) {var result ="
 
 
 
  
  
"; Result + ="
  
  "; For (var I = 0; I 
   ";} Result + =" 
  
Name Mobile phone number
"+ Mobilephone +"
"; List. innerHTML = result;} else {list. innerHTML =" the current data is empty. Join the contact quickly ";}}};


The Web Storage mechanism (Web Storage) of HTML5 practice and analysis has been introduced to you. Web Storage is used for persistent data Storage. Web Storage is generated to overcome some restrictions brought by cookies. The emergence of Web Storage is a revolution in data Storage. More HTML5-related knowledge can be found at Menglong xiaozhan.






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.