HTML5WebStorage (HTML5 Local Storage Technology) _ CSS/HTML

Source: Internet
Author: User
One of the most important skills in HTML5 is HTML5 local storage. Today we will talk about this technology and its comparison with other storage solutions. WebStorage is one of the solutions for local storage in HTML5. It is unreliable to see the names of IE User Data, Flash cookies, and Google Gears before the introduction of the WebStorage concept in HTML5, browser-compatible local storage only uses cookies. Some may ask why the concept of WebStorage should be introduced in the context of local cookie storage?

Is the Cookie swollen?

Cookie defects are obvious.

1. data size: as a storage container, the cookie size is limited to around 4 kb, which is very difficult, especially for the complex business logic requirements, the size of 4 kb Not only stores some configuration fields but also simple single-value information. For most developers, I really don't know what to expect.
2. Security: Because the cookie in the HTTP request is transmitted in plain text (HTTPS is not), the security problem is still very high.
3. network burden: We know that cookies will be appended to each HTTP request and will be transmitted in the HttpRequest and HttpResponse headers. Therefore, unnecessary traffic loss is added.

WebStorage

WebStorage is one of the new local storage solutions for HTML, but it is not a standard designed to replace cookies. As part of the HTTP protocol, cookies are indispensable for processing client-to-server communication, session is the client state persistence that relies on implementation. The intention of WebStorage is to solve the problem that the cookie should not be used, but the local storage of the cookie has to be used.
WebStorage provides two types of Apis: localStorage and sessionStorage. The difference between the two depends on the name. localStorage permanently stores data locally, unless it is explicitly deleted or cleared, the data stored by sessionStorage is valid only during the session. If the browser is closed, the data is automatically deleted. Both objects have common APIs.

The Code is as follows:


Interface Storage {
Readonly attribute unsigned long length;
DOMString? Key (unsigned long index );
Getter DOMString getItem (DOMString key );
Setter creator void setItem (DOMString key, DOMString value );
Deleter void removeItem (DOMString key );
Void clear ();
};

1. length: unique attribute, read-only, used to obtain the number of key-value pairs in storage.
2. key: Obtain the storage key name based on the index
3. getItem: Get the corresponding value in the storage according to the key
4. setItem: Add key-value pairs to storage
5. removeItem: delete a key-Value Pair Based on the key name.
6. clear: clear the storage object

How to Use WebStorage

In the browser that implements WebStorage, the page has two global objects: localStorage and sessionStorage.

Take localStorage as an example to see a simple operation code

The Code is as follows:


Var ls = localStorage;
Console. log (ls. length); // 0
Ls. setItem ('name', 'byron ');
Ls. setItem ('age', '24 ');
Console. log (ls. length); // 2

// Traverse localStorage
For (var I = 0; I
/*
Age: 24
Name: Byron
*/
Var key = ls. key (I );
Console. log (key + ':' + ls. getItem (key ));
}

Ls. removeItem ('age ');


For (var I = 0; I
/*
Name: Byron
*/
Var key = ls. key (I );
Console. log (key + ':' + ls. getItem (key ));
}
Ls. clear (); // 0
Console. log (ls. length );


Event

At the same time, HTML5 specifies a storage event, which is triggered when WebStorage changes. You can use this event to monitor storage modifications on different pages.

The Code is as follows:


Interface StorageEvent: Event {
Readonly attribute DOMString key;
Readonly attribute DOMString? OldValue;
Readonly attribute DOMString? NewValue;
Readonly attribute DOMString url;
Readonly attribute Storage? StorageArea;
};


1. key: key of the key-Value Pair
2. oldValue: Modify the previous value
3. newValue: the modified value
4. url: The page url that triggers the change
5. StorageArea: Storage changed

Defined in index. php

The Code is as follows:


Test

The Code is as follows:


Window. addEventListener ('store', function (e ){
Console. log (e. key + 'is changed form' + e. oldValue + 'to' + e. newValue + 'by' + e. url );
Console. log (e. storageArea = localStorage );
}, False );

LocalStorage. setItem ('username', 'byron ');

Test. php

The Code is as follows:


LocalStorage. setItem ('username', 'casper ');

On the index. php page, click the link to access test. php. You can see the index. php console output log:
UserName is changed form Byron to Casper by http: // localhost/test. php
True

Why is it better than cookie?

1. Calmly speaking, WebStorage generally provides 5 MB of storage space in browsers, which is insufficient for storing videos and images. However, most operations are sufficient.
2. In terms of security, WebStorage is not a browser sent as an HTTP header, so it is relatively secure.
3. In terms of traffic, because WebStorage is not transferred to the server, unnecessary traffic can be saved, which is good for frequently accessed webpages or mobile devices.
This does not mean that WebStorage can replace cookies. Instead, with WebStorage, the cookie can only do what it should do-as a channel for client-server interaction to maintain the client status. Therefore, WebStorage is better than cookie as a local storage solution.

Notes

1. browser compatibility. This is the easiest way to implement almost all new HTML5 features. Because IE8 + browsers support this feature, IE User Data can be used in IE7 and IE6.

2. because localStorage and sessionStorage are both objects, I am hungry and can use them every year ". key "or" [key] ", but this is not recommended.

The Code is as follows:


LocalStorage. userName = 'frank ';
Console. log (localStorage ['username']);


3. Although localStorage is stored locally, different browsers store data independently. Therefore, localStorage stored on Chrome cannot be obtained on FireFox.
4. localStorage and sessionStorage can only store string types. For complex objects, you can use stringify and parse of JSON objects provided by ECMAScript. For earlier IE versions, you can use json2.js.
5. In addition to the console, Chrome also provides a very intuitive display mode for local storage, which is convenient for debugging.

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.