Storing data on the client can solve many problems and reduce unnecessary data transmission:
1. Can save the status of the program: the user can know where he works after closing the browser and opening it.
2. Can cache data: There is no need to obtain a lot of data that will not change from the server every time.
3. Can save user preferences: This kind of data usually does not need to be present on the server.
Previous practicesBefore HTML5 local storage, if we want to save persistent data on the client, there are several options:
1. HTTP cookies. The disadvantage of HTTP cookies is obvious. They can only store up to 4KB of data, and each HTTP request will be sent back to the server and transmitted plain text (unless you use SSL).
2. IE userData. userData is a local storage solution launched by Microsoft during the browser war in the 1990s. It uses the behaviour attribute of DHTML to store local data, allowing each page to store up to 64K data and up to 640K data per site. The disadvantages of userData are obvious. It is not part of the web standard. Unless your program only needs to support IE, it is basically useless.
3. Flash cookies. Flash cookies are actually not the same as HTTP cookies. Perhaps its name should be Flash local storage. Flash cookies allow each site to store data no more than 100K by default. If it exceeds it, Flash will automatically request a larger storage space from the user. With Flash's ExternalInterface interface, you can easily operate Flash's local storage through Javascript. The problem with Flash is very simple, because 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 built-in embedded SQL database based on SQLite and provides a unified API to access the database. After obtaining user authorization, each site can store unlimited data in the SQL database. Gears's problem is that Google itself no longer uses it.
The dazzling variety of technologies leads to browser compatibility issues. The most common cookies here may be cookies.
A new experience in HTML5In response to the above problems, HTML5 provides a more ideal solution: if you need to store data that can be solved simply by using key/value pairs, you can use Web Storage.
Compared with cookies, Web Storage has many advantages, summarized as follows:
1. Larger storage space: Each independent storage space under IE8 is 10M, and other browsers have slightly different implementations, but they are much larger than cookies.
2. The stored content will not be sent to the server: When a cookie is set, the content of the cookie will be sent along with the request on the server, which is a waste of bandwidth for locally stored data. The data in Web Storage only exists locally and will not interact with the server.
3. More rich and easy-to-use interfaces: Web Storage provides a richer set of interfaces, making data operation easier.
4. Independent storage space: Each domain (including subdomain) has independent storage space, and each storage space is completely independent, so it will not cause data confusion.
Web Storage ClassificationWeb Storage actually consists of two parts: sessionStorage and localStorage.
sessionStorage is used to store data in a session locally, which can only be accessed on pages in the same session and the data will be destroyed after the session is finished. Therefore, sessionStorage is not a persistent local storage, but only a session-level storage.
localStorage is used for persistent local storage, and the data will never expire unless it is actively deleted.
Check whether Web Storage is supportedWeb Storage is supported in major mainstream browsers, but in order to be compatible with old browsers, we still need to check whether this technology can be used.
The first method: Check whether the browser supports Web Storage by checking whether the Storage object exists:
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, such as checking whether localStorage supports it:
if (typeof(localStorage) == 'undefined' ) {
alert('Your browser does not support HTML5 localStorage. Try upgrade.');
} 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 upgrade.');
}
or
if (!!localStorage) {
// Yes! localStorage and sessionStorage support!
// Some code...
} else {
alert('Your browser does not support HTML5 localStorage. Try upgrade.');
}
Obviously, the first method is the most direct and simplest.
Use of Web StorageWeb Storage stores key-value pairs, and the browser stores it as a string. Remember to convert them to other formats when necessary.
Except for the different uses of sessionStorage and localStorage, the member list is the same:
key = value: store key value pairs
setItem(key, value): Save key-value pairs
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
Here we still need to emphasize: the value type in the setItem(key,value) method can theoretically be of any type, but in fact the browser will call the value toString method to obtain its string value and store it locally. Therefore, if it is a custom type, you need to define a meaningful toString method by yourself. For example, the following example is used in conjunction with JSON.stringify:
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 strings
* JSON.stringify({'name': 'fred', 'age': 24}); // '{"name":"fred","age":24}'
* JSON.stringify(['a', 'b', 'c']); // '["a","b","c"]'
* JSON.parse, anti-solving JSON.stringify
* JSON.parse('["a","b","c"]') // ["a","b","c"]
*/
In addition, when adding key-value pairs, if the number of added is large, it is safer to check whether there are any exceptions that exceed the limit:
try {
localStorage.setItem(itemId, values.join(';'));
} catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert('Quota exceeded!');
}
}
The method of Web Storage is very simple. The following example is to count the number of clicks on the button:
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter()
{
if(typeof(Storage)!=="undefined")
{
if (localStorage.clickcount)
{
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else
{
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
}
else
{
document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
</body>
</html>
In the example above, you can change localStorage to sessionStorage, click on the button several times and verify the effect before and after closing the browser.
Existing problemsThe defects of Web Storage are mainly concentrated in its security, which are reflected in the following two points:
1. The browser will allocate independent storage space for each domain, that is, the script cannot access the storage space in domain B in domain A, but the browser will not check whether the domain where the script is located is the same as the current domain. That is, scripts embedded in domain A in domain B can still access the data in domain B.
2. The data stored locally is not encrypted and will never expire, which is very easy to cause privacy leakage.
In addition, for more security-related issues, please refer to the link in the practical reference later.
A list of other specifications (for understanding only, maybe it will disappear at any time)Web Database
In the old HTML5 proposal, if you need to store complex data, you can use Web Database, which can use SQL like a client program (the Web Database standard has been abandoned, so here is a brief mention); globalStorageThis is also proposed in html5. After the browser is closed, the information stored using globalStorage can still be retained. Like localStorage, the information stored on 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 be read and written 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 be read and written through this namespace storage object.
Method properties:
• setItem(key, value) - Set or reset the key value.
• getItem(key) - Gets the key value.
• removeItem(key) - Removes the key value.
• Set the key value: window.globalStorage[planabc.net].key = value;
• Get the key value: value = window.globalStorage[planabc.net].key;
Other features:
• The expiration time is the same as localStorage, and some other features are also similar to localStorage.
• Firefox now only supports globalStorage storage under the current domain. Using a common domain will cause a similar error Security error code: 1000.
IndexedDBFinally, we want to introduce IndexedDB. Compared with the other two specifications, only Firefox currently implements IndexedDB (by the way, Mozilla says they will never implement Web SQL Database), but Google has said it is considering adding IndexDB support to Chrome.
IndexedDB introduces the concept of an object store, which is a bit like a SQL Database where you can store records in the database, and each record can have many fields, each field has a specific data type, you can choose a subset of records and traverse it with the cursor, while all changes in the object store are transaction-based.
For more information, please refer to the documentation about IndexedDB in FireFox in the usage reference later.
Practical reference:Official document: http://www.w3schools.com/html5/
Template worries: http://www.CuoXIn.com/w3school/html5/
Security of local storage: http://www.mhtml5.com/2012/03/4586.html
FireFox's experimental features IndexedDB: https://developer.mozilla.org/en-US/docs/IndexedDB