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

WBOY
WBOYOriginal
2016-05-16 15:50:011390browse
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:

Copy the code
The code is as follows:

var person = {'name': 'rainman', 'age': 24};
localStorage.setItem("me", JSON.stringify(person));
JSON.parse(localStorage.getItem( 'me')).name; // 'rainman'
/**
* JSON.stringify, convert JSON data into string
* JSON.stringify({'name': 'fred', 'age': 24}); // '{"name":"fred ","age":24}'
* JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
* JSON.parse, reverse JSON.stringify
* JSON.parse('["a","b","c"]') // ["a","b","c" ]
*/

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).





In the above example, you can replace localStorage with sessionStorage, click the button a few times and verify the effect before and after closing the browser.
Existing Problems
The flaws of Web Storage are mainly focused on its security, which is specifically reflected in the following two points:
1. The browser will allocate independent storage for each domain space, that is, the script in domain A cannot access the storage space in domain B, but the browser will not check whether the domain where the script is located is the same as the current domain. That is, a script embedded in domain A in domain B can still access the data in domain B.
2. Data stored locally is not encrypted and will never expire, which can easily cause privacy leaks.
In addition, for more security-related issues, please refer to the links in the practical reference below.
List of other specifications (for information only, maybe it will be gone when)
Web Database
In the old HTML5 proposal, you can use it if you need to store complex data Web Database can use SQL like a client program (the Web Database standard has been abandoned, so I will briefly mention it here);
globalStorage
This is also proposed in html5 and closed in the browser In the future, the information stored using globalStorage can still be retained. Like localStorage, the information stored in any page in the domain can be shared by all pages, but currently only FireFox supports it.
Basic syntax:
• globalStorage['developer.mozilla.org'] - All subdomains under developer.mozilla.org can read and write through this namespace storage object.
• globalStorage['mozilla.org'] - All web pages under the mozilla.org domain name can be read and written through this namespace storage object.
• globalStorage['org'] - All web pages under the .org domain name can be read and written through this namespace storage object.
• globalStorage[''] - Any web page under any domain name can read and write through this namespace storage object
Method attributes:
• setItem(key, value) - Set Or reset the key value.
• getItem(key) – Get key value.
• removeItem(key) – Remove the key value.
• Set key value: window.globalStorage["planabc.net"].key = value;
• Get key value: value = window.globalStorage["planabc.net"].key;
Others Features:
• The expiration time is the same as localStorage, and some other features are also similar to localStorage.
• Currently, Firefox only supports globalStorage storage under the current domain. If you use the public domain, it will cause an error similar to "Security error" code: "1000".
IndexedDB
The last thing we want to introduce is IndexedDB. Compared with the other two specifications, only Firefox currently implements IndexedDB (by the way, Mozilla said they will never implement Web SQL Database), but Google has stated that it is considering adding IndexDB support to Chrome.
IndexedDB introduces the concept of an object store, which is a bit like a SQL Database. You can store "records" in the "database", and each "record" can have many "fields", each field has For a specific data type, you can select a subset of records and traverse them using the "cursor", and all changes in the object store are based on "transactions".
For more information, see the documentation on IndexedDB in FireFox in the usage reference later.
Practical reference:
Official documentation: http://www.w3schools.com/html5/
Script House: http:// www.jb51.net/w3school/html5/
Local storage security:http://www.mhtml5.com/2012/03/4586.html
FireFox Experimental feature IndexedDB: https://developer.mozilla.org/en-US/docs/IndexedDB
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn