HTTP flood HTML5 Javascript API extension 3-new local storage experience

Source: Internet
Author: User
Tags http cookie in domain web database sessionstorage

Comments: Storing data on the client can solve many problems and reduce unnecessary data transmission: the previous practices of saving the state of a program, caching data, and user preferences are very complicated. Next, I will introduce in detail some of my friends who are interested in it, it may be helpful to youWhy store data to the client?
Storing data on the client can solve many problems and reduce unnecessary data transmission:
1. Saving the state of the program: the user can close the browser and then open it to know where he is working.
2. Data Caching: there is no need to retrieve a lot of unchanged data from the server every time.
3. Save users' preferences: This data usually does not need to be stored on the server.
Previous practices
Before HTML5 local storage, if we want to save persistent data on the client, there are several options:
1. HTTP cookie. The disadvantage of HTTP cookie is obvious. A maximum of 4 kb of data can be stored. Each HTTP request is sent back to the server for plaintext transmission (unless you use SSL ).
2. IE userData. UserData is a local storage solution launched by Microsoft in the browser World War in the S. It stores local data with the behaviour attribute of DHTML, allowing each page to store up to 64 K data, and each site can store up to k Data, the disadvantage of userData is obvious. It is not part of the Web standard, unless your program only needs to support IE, it is basically useless.
3. Flash cookie. Flash cookies are not the same as HTTP cookies. They may be called "Flash local storage". By default, Flash cookies allow each site to store up to KB of data, flash will automatically request a larger storage space from users. With the Flash ExternalInterface interface, you can easily operate the Flash local storage through Javascript. Flash is a simple problem because it is Flash.
4. Google Gears. Gears is an open-source browser plug-in released by Google in. It aims to improve the compatibility of various browsers. Gears has a built-in SQLite-based embedded SQL database, A unified API is provided to access the database. After obtaining user authorization, each site can store unlimited data in the SQL database. The problem with Gears is that Google does not need it any more.
Browser compatibility issues are caused by various dazzling technologies. The most common use here is the cookie.
New HTML5 experience
To address the above problems, HTML5 provides a more ideal solution: If you only need to store data that can be simply solved using key/value pairs, you can use Web Storage.
Compared with cookies, Web Storage has many advantages, which are summarized as follows:
1. Larger storage space: each independent storage space in IE8 is 10 MB. the implementations of other browsers are slightly different, but they are much larger than cookies.
2. The stored content will not be sent to the server: When a Cookie is set, the Cookie content will be sent along with the request to the server, which is a waste of bandwidth for local storage data. The data in Web Storage only exists locally and does not interact with the server.
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, and each storage space is completely independent, so it will not cause data confusion.
Web Storage Classification
Web Storage consists of sessionStorage and localStorage.
SessionStorage is used to locally store data in a session. The data can be accessed only on pages in the same session. When the session ends, the data is also destroyed. SessionStorage is not a persistent local storage, but a session-level storage.
LocalStorage is used for persistent local storage. Unless data is actively deleted, the data will never expire.
Check whether Web Storage is supported
Web Storage is supported by mainstream browsers, but to be compatible with old browsers, check whether this technology can be used.
Method 1: Check whether the browser supports Web Storage by checking whether the Storage object exists:

The Code is as follows:
If (typeof (Storage )! = "Undefined "){
// Yes! LocalStorage and sessionStorage support!
// Some code .....
} Else {
// Sorry! No web storage support ..
}

The second method is to check the respective objects, for example, whether localStorage is supported:

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 ('localstore' in window & window ['localstore']! = 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 method is the most direct and simple.
Use of Web Storage
The Web Storage stores key-value pairs, and the browser stores them as strings. Remember to convert them into other formats when necessary.
Apart from different purposes, sessionStorage and localStorage have the same member list:

The Code is as follows:
Key = value: storage key-value Pair
SetItem (key, value): stores key-value pairs
GetItem (key): key-Value Pair
RemoveItem (key): removes all key-value pairs.
Clear (): clear all key-value pairs
Length: number of key-value pairs

The value type in the setItem (key, value) method can be any type in theory, however, the browser will actually 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 combination with JSON. stringify:

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 converts JSON data into strings
* JSON. stringify ({'name': 'fred ', 'age': 24}); //' {"name": "fred", "age": 24 }'
* JSON. stringify (['A', 'B', 'C']); // '["a", "B", "c"]'
* JSON. parse: reverse parses JSON. stringify
* JSON. parse ('["a", "B", "c"]') // ["a", "B", "c"]
*/

In addition, when you add a key-value pair, if you add a large number of values, it is safer to check for exceptions that exceed the limit:

The Code is as follows:
Try {
LocalStorage. setItem (itemId, values. join (';'));
} Catch (e ){
If (e = QUOTA_EXCEEDED_ERR ){
Alert ('quota exceeded! ');
}
}

The Web Storage method is very simple. The following example is to count the number of button Clicks:

The Code is as follows:
<! 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 above example, you can replace localStorage with sessionStorage, click the button several times, and then verify the effect before and after the browser is closed.
Problems
The defects of Web Storage mainly focus on its security, which is embodied in the following two points:
1. the browser allocates an independent storage space for each domain, that is, the script cannot access the bucket in Domain B in Domain, however, the browser does not check whether the script is in the same domain as the current domain. That is, scripts embedded in Domain A in Domain B can still access data in Domain B.
2. Data stored locally is not encrypted and will never expire, which can easily cause privacy leakage.
For more security-related questions, see the link in the following practical reference.
Other Specifications)
Web Database
In the old HTML5 proposal, if you need to store complex data, you can use Web Database. You can use SQL like a client program, here is a brief introduction );
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, currently, only FireFox is supported.
Basic Syntax:
• GlobalStorage ['developer .mozilla.org '] -- all subdomains under pai.mozilla.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;
Other features:
• The expiration time is the same as that of localStorage, and 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 ".
IndexedDB
Finally, we will introduce IndexedDB. Compared with the other two specifications, currently only Firefox has implemented IndexedDB (by the way, Mozilla says they will never implement Web SQL databases ), however, Google has already said that it is considering adding IndexDB support to Chrome.
IndexedDB introduces the concept of an object store, which is a bit like an SQL Database. You can store "records" in "databases ", in addition, each "record" can have many "fields". Each field has a specific data type. You can select a subset of the record and use the "cursor" to traverse it, at the same time, all changes in the object store are based on transactions.
For more information, see the IndexedDB document in FireFox.
Practical reference:
Official documents: http://www.w3schools.com/html5/
Feet home: http://www.jb51.net/w3school/html5/
Security of Local Storage: http://www.mhtml5.com/2012/03/4586.html
Experimental features of FireFox IndexedDB: https://developer.mozilla.org/en-US/docs/IndexedDB

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.