Go HTML5 Local Storage

Source: Internet
Author: User
Tags send cookies sessionstorage

    • 1, Sessionstorage
    • 2, Localstorage
    • 3. Database Storage
    • 4, Globalstorage
    • 5. Compatibility
    • Reference documents

Local persistent storage has always been an aspect of a local client program over a Web program. For local applications, the operating system has an abstraction layer that stores and obtains application-specific data, such as user settings or run-time state. These values can be stored in the registry, INI file, or somewhere else, depending on the implementation of the operating system. If your on-premises application needs to be not simply a local store of key-value pairs, you can also use an embedded database, invent your own file format, or a number of other solutions (quoted in the HTML5 local storage explained).

HTML5 Storage provides a way for websites to store information on your local computer and get it later when needed. This concept is similar to a cookie, except that it is designed for larger capacity storage. The size of the cookie is limited, and every time you request a new page, the cookie will be sent past. HTML5 's storage is stored on your computer, and the Web site can get that data through JavaScript after the page has finished loading.

1, Sessionstorage
!! Window.sessionstorage;
Common methods
. Key = value
. SetItem (key, value)
. GetItem (Key)
. RemoveItem (Key)
. Clear ()
Window.sessionStorage.name = ' Rainman ';           Assignment Window.sessionStorage.setItem (' name ', ' Cnblogs ');  Assign a value of Window.sessionStorage.getItem (' name ');            Value Window.sessionStorage.removeItem (' name ');         Remove value window.sessionStorage.clear ();                    Delete all Sessionstorage
Event: Window.onstorage
detection is worth changing, browser support is not good.
    1. The storage limit of the cookie is within 4k, compared to the session storage has a larger storage space, but as to the specific size, this should refer to the specific implementation of the browser manufacturer.
    2. The cookie has a mechanism to send cookies to the server every time a client requests a server, which will undoubtedly do a lot of unnecessary work, since not every request for the server requires all of the cookie information, and session storage solves the problem very well. , it does not take the form of automatic sending, which reduces unnecessary work.
    3. The life cycle of the data stored by Sessionstorage is similar to the session, and the data does not exist after the browser (or tab) is closed. However, the sessionstorage still exists after refreshing the page or using the forward, Back button.
    4. Session storage Each window's value is independent (each window has its own data), its data will disappear as the window closes, the sessionstorage between the windows can not be shared.
    5. The key and value in SetItem are stored in the form of a string. That is, if you have the following code: SetItem (' count ', 1); by GetItem (' count ') + 5 will not be expected 6 (integer), but ' 16 ' (string).
    6. When you use SetItem again to set the value of a key that already exists, the new value replaces the old value.
    7. When the data in the store changes, the corresponding event (window.onstorage) is triggered, but the current browser support for this event is not perfect and can be ignored for the time being.
2, Localstorage
!! Window.localstorage;

Method is the same as Sessionstorage

    1. The local storage only stores the data on the server that the client uses and will not be sent (unless you intentionally do so).
    2. And for a domain, the local storage is shared (multiple Windows share a "database").
    3. Localstorage is used for persistent local storage, and the data is never expired unless the data is actively deleted.
Combine json.stringify using more powerful var person = {' name ': ' Rainman ', ' Age ': 24};localstorage.setitem ("Me", json.stringify (person)) ; Json.parse (Localstorage.getitem (' Me)). name;//' Rainman '/** * json.stringify, convert JSON data to String *     json.stringify ({' Name ': ' Fred ', ' Age ': +});   ' {' name ': ' Fred ', ' Age ': ' * json.stringify '     ([' A ', ' B ', ' C ']);               ' [' A ', ' B ', ' C '] ' * json.parse, inverse json.stringify *     json.parse (' ["A", "B", "C"] ')                    //["A", "B", "C"] */
3. Database Storage

For simple data storage, using Sessionstorage and Localstorage is a good way to do it, but it is grasp to deal with trivial relational data. This is where HTML 5 's "Web SQL Database" API interface is used.

A. Open 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.");                         Detect if the connection was created successfully

The above code creates a database object db with a name of Todo and a version number of 0.1. The DB also carries descriptive information and approximate size values. If necessary, this size can be changed, so there is no need to pre-assume how much space is allowed for the user.

You can never assume that the connection has been successfully established, even if it was successful for a user in the past. Why a connection fails for multiple reasons. Perhaps the user agent denies your access for security reasons, perhaps the device storage is limited. In the face of an active and rapidly evolving potential user agent, it is unwise to make assumptions about the user's machine, software, and capabilities. For example, when users use handheld devices, they can freely dispose of data that is only a few megabytes.

B, execute the query
Db.transaction (Function (TX) {     tx.executesql (        "INSERT into ToDo (label, timestamp) VALUES (?,?)",         [' Lebel ' , New Date (). GetTime ()],         function (TX2, result) {alert (' Success ');},         function (TX2, error) {alert (' failed: ' + Error.message); }    
    1. The Execute SQL statement uses the database.transaction () function, which has only one parameter that is responsible for executing the query function.
    2. The function has a parameter of type Transaction (TX).
    3. The transaction parameter (TX) has a function: ExecuteSQL (). This function uses four parameters: The SQL string that represents the query, the string data where the question mark is inserted into the query, a function that executes on success, and a function that executes when it fails.
    4. The successful function has two parameters: TX2, transactional parameters; result, returned results of execution, structure
    5. The successful function also has two parameters: TX2, transactional parameter; error, wrong object, structure
C, other
    • Chrome support; Firefox (beta version 4.01) is not supported; IE8 is not supported.
D. Example
Create 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 Table Db.transaction (function (TX) {tx.executesql ("CREATE table IF not EXISTS users (ID REAL UNIQUE, name TEX T) ", [], function () {alert (' Create the Users Table succeeds ');}, function (TX, error) {alert (' Create Users table failed: ' + error.mess Age); }    );}); Insert Data db.transaction (function (TX) {tx.executesql ("INSERT into users (ID, name) VALUES (?,?)", [Math. Random (), ' space '], function () {alert (' Insert data succeeded '), function (TX, error) {alert (' Insert data failed: ' + error.message)    ;} ); });            Query Db.transaction (function (TX) {tx.executesql ("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); }    ); }); Delete Table db.transaction (function (TX) {tx.executesql (' DROP table users ');});
4, Globalstorage

This is also proposed in HTML5, after the browser is closed, the use of globalstorage stored information can still be preserved, like localstorage, any page in the domain stored information can be shared by all pages

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 the pages under the mozilla.org domain name can be read and written through this namespace store object.
    • globalstorage[' org ']--all pages under the. org domain name can be read and written through this namespace store object.
    • globalstorage[']--any page under any domain name can be read and written through this namespace store object
Method Properties
    • SetItem (key, value)--Sets or resets the key value.
    • GetItem (key)--Gets the key value.
    • RemoveItem (key)--Deletes the key value.
    • Set key value: window.globalstorage["planabc.net"].key = value;
    • Gets the key value: value = window.globalstorage["Planabc.net"].key;
    • The expiration time is the same as localstorage, and some other features are similar to Localstorage.
    • Now Firefox only supports Globalstorage storage under the current domain, if using a common domain causes one such a similar error "Security error" code: "1000".
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 -- -- --
Reference documents
    • HTML5 Local storage explanation
    • HTML 5 Web SQL Database discussion
    • Web Storage full resolution
    • Firefox Developer:dom St Orage
    • Cross-browser local storage (ii): Dom:storage
    • UserData behavior (UserData Behavior)
    • Common Browser Local storage comparison of several scenarios

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.