Home >
Article > Web Front-end > Raid on HTML5 Javascript API Extension 3—a new experience of local storage_html5 tutorial skills
Raid on HTML5 Javascript API Extension 3—a new experience of local storage_html5 tutorial skills
WBOYOriginal
2016-05-16 15:50:011393browse
Why do we need to save data to the client? Storing data on the client can solve many problems and reduce unnecessary transmission of data: 1. Can save the status of the program: the user can know where he has been working after closing the browser and opening it again. 2. Ability to cache data: There is no need to obtain data from the server every time for a lot of data that does not change. 3. Can save user preferences: This kind of data usually does not need to be stored on the server. Previous approach Before HTML5 local storage, if we wanted to save persistent data on the client, we had several options: 1. HTTP cookie. The disadvantages of HTTP cookies are obvious, they can only store up to 4KB of data, and each HTTP request will be transmitted back to the server in clear text (unless you use SSL). 2. IE userData. userData is a local storage solution launched by Microsoft during the browser wars of the 1990s. It uses the behavior attribute of DHTML to store local data. It allows each page to store up to 64K data and each site to store up to 640K data. The shortcomings of userData are obvious. It's not part of the web standards, so unless your application only needs to support IE, it's of little use. 3. Flash cookies. Flash cookie is actually not the same thing as HTTP cookie. Perhaps its name should be called "Flash local storage". Flash cookie allows each website to store no more than 100K of data by default. If it exceeds, Flash will automatically request an update from the user. Large storage space, with the help of Flash's ExternalInterface interface, you can easily operate Flash's local storage through Javascript. The problem with Flash is simply that it is Flash. 4. Google Gears. Gears is an open source browser plug-in released by Google in 2007, aiming to improve the compatibility of major browsers. Gears has a built-in embedded SQL database based on SQLite and provides a unified API to access the database. After obtaining users After authorization, each site can store data of any size in the SQL database. The problem with Gears is that Google itself no longer uses it. The dazzling variety of technologies leads to browser compatibility issues. Probably the thing that everyone uses the most here is cookies. New experience in HTML5 In response to the above problems, HTML5 provides a more ideal solution: if what you need to store is simply a key/value pair, it can be solved data, you can use Web Storage. Compared with Cookies, Web Storage has many advantages, which can be summarized as follows: 1. Larger storage space: Each independent storage space under IE8 is 10M, and other browsers have slightly different implementations , but are much larger than Cookie. 2. The stored content will not be sent to the server: When a cookie is set, the cookie content will be sent to the server along with the request, which is a waste of bandwidth for locally stored data. The data in Web Storage only exists locally and does not interact with the server in any way. 3. More rich and easy-to-use interfaces: Web Storage provides a richer set of interfaces, making data operations easier. 4. Independent storage space: Each domain (including subdomains) has an independent storage space. Each storage space is completely independent, so there will be no data confusion. Web Storage Classification Web Storage actually consists of two parts: sessionStorage and localStorage. sessionStorage is used to locally store data in a session. These data can only be accessed by pages in the same session and the data will be destroyed when the session ends. Therefore sessionStorage is not a persistent local storage, only session-level storage. LocalStorage is used for persistent local storage. Unless the data is actively deleted, the data will never expire. Check whether Web Storage is supported Web Storage is supported in all major browsers, but in order to be compatible with older browsers, you still need to check whether this technology can be used. First way: Check whether the browser supports Web Storage by checking whether the Storage object exists:
Copy code
The code is as follows:
if(typeof(Storage)!=="undefined"){ // Yes! localStorage and sessionStorage support! // Some code... .. } else { // Sorry! No web storage support.. }
The second way is to check the respective objects separately, for example, check whether localStorage supports :
Copy the code
The code is as follows:
if (typeof(localStorage) == 'undefined' ) { alert('Your browser does not support HTML5 localStorage. Try upgrading.'); } else { // Yes! localStorage and sessionStorage support! // Some code..... } or: if('localStorage' in window && window['localStorage'] !== null) { // Yes! localStorage and sessionStorage support! // Some code..... } else { alert('Your browser does not support HTML5 localStorage. Try upgrading.') ; } or if (!!localStorage) { // Yes! localStorage and sessionStorage support! // Some code..... } else { alert('Your browser does not support HTML5 localStorage. Try upgrading.'); }
Obviously the first way is the most direct and simplest. Usage of Web Storage Web Storage stores key-value pairs, and the browser stores them as strings. Remember to convert them to other formats if necessary. Except for different uses, sessionStorage and localStorage have the same member list:
Copy code
The code is as follows:
key = value: store key-value pair setItem(key, value): store key-value pair getItem(key): get key-value pair removeItem(key ): Remove all key-value pairs clear(): Clear all key-value pairs length: The number of key-value pairs
It should be emphasized here: setItem(key,value ) method can be any type in theory, but in fact the browser will call the toString method of value to obtain its string value and store it locally, so if it is a custom type, you need to define a meaningful one yourself toString method. For example, the following example is used in combination with JSON.stringify:
In addition, when adding key-value pairs, if the number added is relatively large, compare The safe way is to check whether there is an exception exceeding the limit:
Copy the code
The code is as follows:
try { localStorage.setItem(itemId, values.join(';')); } catch (e) { if (e == QUOTA_EXCEEDED_ERR) { alert( 'Quota exceeded!'); } }
Web Storage's method is very simple. The following example counts the number of button clicks:
Copy code
The code is as follows:
< ;head> <script> <br>function clickCounter() <br>{ <br>if(typeof(Storage)!=="undefined") <br>{ <br>if (localStorage.clickcount) <br>{ <br>localStorage.clickcount=Number(localStorage.clickcount) 1; <br>} <br>else <br>{ <br>localStorage.clickcount=1; <br>} <br>document.getElementById ("result").innerHTML="You have clicked the button " localStorage.clickcount " time(s)."; <br>} <br>else <br>{ <br>document.getElementById("result"). innerHTML="Sorry, your browser does not support web storage..."; <br>} <br>} <br></script>
< /div>
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).