HTML5 local storage localStorage, sessionStorage and IE exclusive UserData, html5localstorage

Source: Internet
Author: User
Tags sessionstorage

HTML5 local storage localStorage, sessionStorage and IE exclusive UserData, html5localstorage
HTML5 local storage localStorage, sessionStorage and IE exclusive UserData

The most common method for storing data on the client is non-cookie. With the popularity of HTML5, the new local storage methods localStorage and sessionStorage will be used in standard browsers. LocalStorage and sessionStorage are one of the new HTML5 features. In fact, Microsoft has already supported the localStorage and sessionStorage APIs as early as Internet Explorer 8, when testing these two APIs in IE8 and 9, you must test them in the server environment and report an error in the local environment.

1. What is localStorage?

LocalStorage is used for persistent local storage. Data never expires unless data is manually deleted.

2. What are the advantages of localStorage over cookies?

The following table lists the features of cookies and localStorage.

Features LocalStorage Cookie
Capacity 5 M About 4 K
Compatibility IE8 and later browsers Basically all browsers are compatible
Expiration time Never expire Customizable
Whether to send data to the server along with HTTP No Yes (bandwidth usage)
Scope Sub-domain names are independent of each other You can use. setDomain To Set primary domain name sharing.

LocalStorage has obvious advantages. It has a large capacity and does not occupy bandwidth. In addition, localStorage provides a variety of methods to set, read, and remove data.
LocalStorage. setItem (key, value) // you can specify a key-value pair.
LocalStorage. getItem (key) // read the corresponding value through the key value
LocalStorage. removeItem (key) // remove the corresponding value through the key value
LocalStorage. clear () // initialize localStorage to clear all key-value pairs
LocalStorage. key (index) // obtain the key name of the specified index through subscript index

SessionStorage is similar to localStorage. What is the difference between them? The only difference lies in the persistence of the data they save. The data saved by localStorage never expires. The data saved by sessionStorage disappears after the browser window is closed. If the browser window is not closed, only the page is refreshed, the data stored by sessionStorage still exists. They have the same attributes and methods.

Although sessionStorage and localStorage are so easy to use, they are not supported in IE6 and IE7. We can use the UserData exclusive to IE to make up for this defect. UserData was used by IE browser to locally store data, userData is stored on a disk as a file. UserData needs to be attached to an HTML tag to set, read, and remove data. Not all HTML tags are supported, supported HTML tags include:

A, ABBR, ACRONYM, ADDRESS, AREA, B, BIG, BLOCKQUOTE, BUTTON, CAPTION, CENTER, CITE, CODE, DD, DEL, DFN, DIR, DIV, DL, DT, EM, FONT, FORM, hn, HR, I, IMG, INPUT type = button, INPUT type = checkbox, INPUT type = file, INPUT type = hidden, INPUT type = image, INPUT type = password, INPUT type = radio, INPUT type = reset, INPUT type = submit, INPUT type = text, KBD, LABEL, LI, LISTING, MAP, MARQUEE, MENU, OBJECT, OL, OPT ION, P, PLAINTEXT, PRE, Q, S, SAMP, SELECT, SMALL, SPAN, STRIKE, STRONG, SUB, SUP, TABLE, TEXTAREA, TT, U, UL, VAR, XMP.

UserData has a certain limit on the data size. (For information translated from the MSDN documentation, see the documentation for good English proficiency ):

Site Type Size limit of a single file (KB) Data size limit for a single domain name (KB)
Local Machine 128 1024
Lan 512 10240
Trusted Sites 128 1024
Internet 128 1024
Restricted site 64 640

We can see from the table that to be compatible with various situations, we recommend that the size of a single UserData file not exceed 64 KB.

Using UserData to store data is more difficult than localStorage, but it is still very simple. The process is divided into the following steps:

1. Create HTML tags

2. Add the style behavior to the HTML Tag: url ('# default # userdata') or js sets. addBehavior ("# default # userData") for the HTML object ")

3. Set the data expiration time

4. Load UserData

5. Store data, read data, and delete data

6. Save data to the storage Zone

It is easier to understand the code (Special note: The following code can be called inside the body tag. In the script of the head tag, the system prompts that you do not have the permission. The reason is unknown ):

<script type="text/javascript">    var UserData = {        userData: null,        name: document.location.hostname,        init: function() {            if (!this.userData) {                try {                    this.userData = document.createElement("INPUT");                    this.userData.type = "hidden";                    this.userData.style.display = "none";                    this.userData.addBehavior("#default#userData");                    document.body.appendChild(this.userData);                    var expires = new Date();                    expires.setDate(expires.getDate() + 365);                    this.userData.expires = expires.toUTCString();                } catch (e) {                    return false;                }            }            return true;        },        setItem: function(key, value) {            if (this.init()) {                this.userData.load(this.name);                this.userData.setAttribute(key, value);                this.userData.save(this.name);            }        },        getItem: function(key) {            if (this.init()) {                this.userData.load(this.name);                return this.userData.getAttribute(key)            }        },        remove: function(key) {            if (this.init()) {                this.userData.load(this.name);                this.userData.removeAttribute(key);                this.userData.save(this.name);            }        }    };</script>

Conclusion: when the market share of IE6 and IE7 gradually declines, localStorage and sessionStorage will become more and more widely used. In addition to some necessary situations, cookies can be replaced by localStorage, of course, it is not recommended to store sensitive data in localStorage, because localStorage can be read, modified, or deleted at any time.

Reference: http://www.css88.com/archives/3717

By: Wang meijian from: http://www.cnblogs.com/wangmeijian/p/4518606.html reprint please keep the signature and source!

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.