HTML5 local storage details

Source: Internet
Author: User
Tags sessionstorage

HTML5 storage provides a way for websites to store information on your local computer and obtain it as needed. This concept is similar to cookie. The difference is that it is designed for larger storage capacity.

HTML5storage provides a way for websites to store information on your local computer and obtain the information as needed. This concept is similar to cookie. The difference is that it is designed for larger storage capacity. The Cookie size is limited, and the cookie will be sent every time you request a new page. HTML5 storage is stored on your computer. After a website loads a page, you can use Javascript to obtain the data.

1. sessionStorage

Detection

!! Window. sessionStorage;

Common Methods

. Key = value

. SetItem (key, value)

. GetItem (key)

. RemoveItem (key)

. Clear ()

[Javascript]
1. window. sessionStorage. name = 'rainman '; // value assignment
2. window. sessionStorage. setItem ('name', 'cnblogs'); // value assignment
3. window. sessionStorage. getItem ('name'); // Value
4. window. sessionStorage. removeItem ('name'); // remove the value
5. window. sessionStorage. clear (); // Delete All sessionStorage

Event:

Window. onstorage

Detection is worth changing, and browser support is poor.

Note:

Cookie storage is limited to 4 K. Compared to session storage, session storage has a larger storage space, but the actual size should be determined by the browser vendor.
A mechanism of cookie is to send the cookie to the server every time the client requests the server. This will undoubtedly do a lot of unnecessary operations, because not all cookie information is required for each request server, session storage does not solve this problem automatically, which reduces unnecessary work.
The life cycle of the data stored through sessionStorage is similar to Session. After the browser (or tab) is closed, the data does not exist. However, sessionStorage still exists after you refresh the page or use the forward or backward buttons.
Session storage the values of each window are independent (each window has its own data). Its data disappears as the window closes, and sessionStorage between Windows cannot be shared.
The key and value in setItem are stored as strings. That is to say, if the following code is available: setItem ('Count', 1); what is obtained through getItem ('Count') + 5 is not the expected 6 (integer ), but '16' (string ).
When you use setItem to set the value of an existing key again, the new value replaces the old one.
When the data in the storage changes, the corresponding event (window. onstorage) will be triggered. However, browsers currently do not fully support this event and can be ignored temporarily.
2. localStorage

Detection

!! Window. localStorage;

The method is the same as sessionStorage.

Note:

Local storage stores only the data used by the client and does not send the data to the server (unless you do this intentionally ).
In addition, for a domain, local storage is shared (multiple Windows share a "Database ").
LocalStorage is used for persistent local storage. Unless data is actively deleted, the data will never expire.
Example

[Javascript]
1. // more powerful in combination with JSON. stringify
2. var person = {'name': 'rainman ', 'age': 24 };
3. localStorage. setItem ("me", JSON. stringify (person ));
4. JSON. parse (localStorage. getItem ('me'). name; // 'rainman'
5.
6 ./**
7. * JSON. stringify converts JSON data into strings
8. * JSON. stringify ({'name': 'fred ', 'age': 24}); //' {"name": "fred", "age": 24 }'
9. * JSON. stringify (['A', 'B', 'C']); // '["a", "B", "c"]'
10. * JSON. parse, reverse Decoding of JSON. stringify
11. * JSON. parse ('["a", "B", "c"]') // ["a", "B", "c"]
12 .*/

3. Database Storage

The use of sessionStorage and localStorage for simple data storage can be well completed, but in addition to processing trivial relational data, it is far less powerful. This is the application of the "Web SQL Database" API of HTML 5.

A. Open the link

[Javascript]
1. var db = openDatabase ("ToDo", "0.1", "A lalert of to do items.", 200000); // open the link
2. if (! Db) {alert ("Failed to connect to database.");} // check whether the connection is successfully created.

The code above creates a database object db named Todo with version number 0.1. The db also contains the description and approximate size values. If needed, the size can be changed, so there is no need to preassume how much space the user is allowed to use.

It cannot be assumed that the connection has been successfully established, even if it was successful for a user in the past. There are multiple reasons why a connection fails. Maybe the User Agent rejects your access for security reasons, maybe the device storage is limited. In the face of active and rapidly evolving potential user agents, it is unwise to make assumptions about users' machines, software and capabilities. For example, when a user uses a handheld device, the data they can freely dispose of may only contain a few megabytes.

B. Execute the query


[Javascript]
1. db. transaction (function (tx ){
2. tx.exe cuteSql (
3. "insert into ToDo (label, timestamp) values (?, ?) ",
4. ['lebel ', new Date (). getTime ()],
5. function (tx2, result) {alert ('success ');},
6. function (tx2, error) {alert ('failed: '+ error. message );}
7 .);
8 .});

Execute the SQL statement using the database. transaction () function, which has only one parameter and is responsible for executing the query function.
This function has a transaction type parameter (tx ).
The transaction parameter (tx) has a function: executeSql (). This function uses four parameters:
It indicates the SQL string to be queried. It is inserted into the string data where the question mark is located in the query. It is a function executed when the query is successful and a function executed when the query fails.
The successfully executed function has two parameters: tx2, transactional parameter; result, returned result, and structure.
The successfully executed function also has two parameters: tx2, transactional parameter; error, error object, and structure.
C. Others

Chrome support; firefox (version 4.01 during testing) does not support; IE8 does not.
D. Example

[Javascript]
1. // create a database
2. var db = openDatabase ("users", "1.0", "User table", 1024*1024 );
3. if (! Db ){
4. alert ("Failed to connect to database .");
5.} else {
6. alert ("connect to database 'K '.");
7 .}
8.
9. // create a table www.2cto.com
10. db. transaction (function (tx ){
11. tx.exe cuteSql (
12. "create table if not exists users (id real unique, name TEXT )",
13. [],
14. function () {alert ('users table created successfully ');},
15. function (tx, error) {alert ('failed to create users table: '+ error. message );}
16 .);
17 .});
18.
19. // insert data
20. db. transaction (function (tx ){
21. tx.exe cuteSql (
22. "insert into users (id, name) values (?, ?) ",
23. [Math. random (), 'space'],
24. function () {alert ('data inserted successfully ');},
25. function (tx, error) {alert ('failed to insert data: '+ error. message );}
26 .);
27 .});
28.
29. // query
30. db. transaction (function (tx ){
31. tx.exe cuteSql (
32. "SELECT * FROM users", [],
33. function (tx, result ){
34. var rows = result. rows, length = rows. length, I = 0;
35. for (I; I <length; I ++ ){
36. alert (
37. 'id = '+ rows. item (I) ['id'] +
38. 'name = '+ rows. item (I) ['name']
39 .);
40 .}
41 .},
42. function (tx, error ){
43. alert ('select Failed: '+ error. message );
44 .}
45 .);
46 .});
47.
48. // Delete the table
49. db. transaction (function (tx ){
50. tx.exe cuteSql ('drop TABLE users ');
51 .});

4. globalStorage

This is also proposed in html5. After the browser is closed, the information stored using globalStorage can still be retained. Like localStorage, information stored on any page in the domain can be shared by all pages.

Basic syntax

GlobalStorage ['developer .w.illa.org '] -- all subdomains under .w.illa.org can read and write through the namespace storage object.
GlobalStorage ['mozilla. org '] -- all webpages under the mozilla.org domain name can read and write through the namespace storage object.
GlobalStorage ['org '] -- all webpages under the. org domain name can read and write through this namespace storage object.
GlobalStorage [''] -- any webpage under any domain name can read and write through this namespace storage object
Method Property

SetItem (key, value) -- sets or resets the key value.
GetItem (key) -- get the key value.
RemoveItem (key) -- delete the key value.
Set the key value: window. globalStorage ["planabc.net"]. key = value;
Obtain the key value: value = window. globalStorage ["planabc.net"]. key;
Others

The expiration time is the same as that of localStorage. Other features are similar to that of localStorage.
Currently, Firefox only supports globalStorage in the current domain. If a public domain is used, a similar error "Security error" code: "1000" may occur ".

5. Compatibility

 

Method Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
LocalStorage 4 2 8 10.50 4
SessionStorage 5 2 8 10.50 4
GlobalStorage -- 2 -- -- --
 
 




From fan Yongqiang's column

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.