Home > Web Front-end > CSS Tutorial > HTML5 WebStorage (HTML5 local storage technology)_CSS/HTML

HTML5 WebStorage (HTML5 local storage technology)_CSS/HTML

WBOY
Release: 2016-05-16 12:04:00
Original
1862 people have browsed it

WebStorage is one of the local storage solutions in HTML5. Before the introduction of the WebStorage concept in HTML5, other unreliable solutions such as IE User Data, Flash Cookies, and Google Gears were removed. It was a browser-compatible local storage solution. Only using cookies. Some students may ask, since we have cookie local storage, why do we need to introduce the concept of WebStorage?

What’s wrong with Cookie

The flaws of cookies are very obvious

1. Data size: As a storage container, the size of cookie is limited to about 4KB, which is very annoying, especially for the current complex business logic requirements. In addition to storing some configuration fields, the 4KB capacity also stores simple single-value information. Most developers really don’t know what to expect.
2. Security issues: Since the cookie in the HTTP request is passed in clear text (HTTPS is not), the security issues are still huge.
3. Network burden: We know that cookies will be attached to each HTTP request and will be transmitted in the headers of HttpRequest and HttpResponse, so some unnecessary traffic losses will be added.

WebStorage

WebStorage is one of the new local storage solutions for HTML, but it is not a standard developed to replace cookies. Cookies are indispensable as part of the HTTP protocol to handle communication between the client and the server. Session is Implementation-dependent client-side state persistence. The purpose of WebStorage is to solve the problem of local storage that should not be done with cookies, but has to use cookies.
WebStorage provides two types of APIs: localStorage and sessionStorage. The difference between the two can be roughly understood by looking at the names. localStorage stores data locally permanently unless it is explicitly deleted or cleared. The data stored in sessionStorage is only in the session. It is valid for a certain period and will be automatically deleted when you close the browser. Both objects have a common API.

Copy code 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: The only attribute, read-only, used to obtain the number of key-value pairs in the storage.
2. key: Get the key name of the storage based on the index
3. getItem: get the corresponding value in the storage based on the key
4. setItem: add a key-value pair to the storage
5. removeItem: Delete the key-value pair according to the key name
6. clear: clear the storage object

How to use WebStorage

In a browser that implements WebStorage, the page has two global objects, localStorage and sessionStorage
HTML5 WebStorage (HTML5 local storage technology)_CSS/HTML
Take localStorage as an example and look at a simple operation code

Copy 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

            //遍历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);

事件

同时HTML5规定了一个storage事件,在WebStorage发生变化的时候触发,可以用此监视不同页面对storage的修改

复制代码 代码如下:

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: the key of the key-value pair
2. oldValue: the value before modification3. newValue: the modified value
4. url: the page url that triggered the change
5. StorageArea: the changed Storage

Defined in index.php

Copy code The code is as follows:

Copy code The code is as follows:

window.addEventListener('storage',function(e ; BR>     },false);
        localStorage.setItem('userName','Byron');

test.php

Copy code The code is as follows:

localStorage.setItem(' userName','Casper');

When you click the link on the index.php page to access test.php, you can see the console output log of index.php:
userName is changed form Byron to Casper by http://localhost/test.php
true

Why it is better than cookies

1. In terms of capacity, WebStorage generally provides 5M of storage space in browsers, which is not enough to store videos and pictures, but it is sufficient for most operations
2. In terms of security, WebStorage does not play a role. HTTP header is sent by the browser, so it is relatively safe
3. In terms of traffic, because WebStorage is not transmitted to the server, unnecessary traffic can be saved, which is still very convenient for high-frequency visits or web pages targeting mobile devices. Not bad.
This does not mean that WebStorage can replace cookies, but that with WebStorage, cookies can only do what it should do - serve as a channel for interaction between the client and the server, and maintain the client state. So WebStorage is superior to cookies just as a local storage solution.

Things to note

1. Browser compatibility, this is almost the easiest to implement among all new HTML5 features, because all IE8 browsers support it. IE7 and IE6 can be implemented using IE User Data.

HTML5 WebStorage (HTML5 local storage technology)_CSS/HTML
2. Since localStorage and sessionStorage are both objects, you can also obtain and modify key-value pairs through ".key" or "[key]", but this is not recommended.
Copy code The code is as follows:

localStorage.userName='Frank';
console.log(localStorage['userName']);

3. Although localStorage is stored locally, different browsers store data independently, so the localStorage stored on Chrome is It is not available on FireFox.
4. localStorage and sessionStorage can only store string types. For complex objects, you can use stringify and parse of the JSON object provided by ECMAScript. For lower versions of IE, you can use json2.js
5. In addition to the console, Chrome also provides a very intuitive display method for local storage, which is very convenient when debugging
HTML5 WebStorage (HTML5 local storage technology)_CSS/HTML
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template