HTML5 local storage and HTML5 Storage

Source: Internet
Author: User
Tags sessionstorage

HTML5 local storage and HTML5 Storage

  • 1. sessionStorage
  • 2. localStorage
  • 3. Database Storage
  • 4. globalStorage
  • 5. Compatibility
  • References

Local persistent storage has always been an advantage of local client programs over web programs. For local applications, the operating system has a total of abstraction layers for storing and retrieving application-specific data, such as user settings or runtime status. These values can be stored in the registry, INI file, or somewhere else, depending on the implementation of the operating system. If your local applications require local storage in the form of key-value pairs, you can also use an embedded database to create your own file format, or many other solutions (refer to "HTML5 local storage details ).

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. 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 ()
Window. sessionStorage. name = 'rainman '; // value window. sessionStorage. setItem ('name', 'cnblogs'); // value window. sessionStorage. getItem ('name'); // value: window. sessionStorage. removeItem ('name'); // remove the value window. sessionStorage. clear (); // Delete All sessionStorage
Event: window. onstorage
Detection is worth changing, and browser support is poor.
Note: 2. localStorage
Detection
!! Window. localStorage;

The method is the same as sessionStorage.

Note: Examples
// JSON. stringify uses more powerful var person = {'name': 'rainman ', 'age': 24}; localStorage. setItem ("me", JSON. stringify (person); JSON. parse (localStorage. getItem ('me ')). name; // 'rainman '/*** JSON. stringify converts JSON data into a string * JSON. stringify ({'name': 'fred ', 'age': 24}); //' {"name": "fred", "age ": 24} '* JSON. stringify (['A', 'B', 'C']); // '["a", "B", "c"]' * JSON. parse, anti-JSON. stringify * JSON. parse ('["a", "B", "c"]') // ["a", "B", "c"] */
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
Var db = openDatabase ("ToDo", "0.1", "A lalert of to do items.", 200000); // open the link 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
Db. transaction (function (tx) {tx.exe cuteSql ("insert into ToDo (label, timestamp) values (?, ?) ", ['Lebel ', new Date (). getTime ()], function (tx2, result) {alert ('success') ;}, function (tx2, error) {alert ('failed: '+ error. message );});});
C. Others
  • Chrome support; firefox (version 4.01 during testing) does not support; IE8 does not.
D. Example
// Create a database var db = openDatabase ("users", "1.0", "User table", 1024*1024); if (! Db) {alert ("Failed to connect to database. ");} else {alert (" connect to database 'K '. ");} // create a table db. transaction (function (tx) {tx.exe cuteSql ("create table if not exists users (id real unique, name TEXT)", [], function () {alert ('users table created successfully');}, function (tx, error) {alert ('failed to create users table: '+ error. message) ;}); // insert data into the database. transaction (function (tx) {tx.exe cuteSql ("insert into users (id, name) value S (?, ?) ", [Math. random (), 'space'], function () {alert ('data inserted successfully');}, function (tx, error) {alert ('data inserted failed: '+ error. message) ;}); // query the database. transaction (function (tx) {tx.exe cuteSql ("SELECT * FROM users", [], function (tx, result) {var rows = result. rows, length = rows. length, I = 0; for (I; I <length; I ++) {alert ('Id = '+ rows. item (I) ['id'] + 'name = '+ rows. item (I) ['name']) ;}, function (tx, error) {alert ('select Failed: '+ error. message) ;}); // deletes the table database. transaction (function (tx) {tx.exe cuteSql ('drop TABLE users ');});
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 -- -- --
References
  • HTML5 local storage details
  • Preliminary Exploration of HTML 5 Web SQL Database
  • Web Storage full resolution
  • Firefox Developer: DOM Storage
  • Cross-browser local Storage (2): DOM: Storage
  • UserData Behavior (userData Behavior)
  • Comparison of local storage solutions for common browsers

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.