HTML5 localstorage Local Storage

Source: Internet
Author: User

Reprinted:

When it comes to local storage, this is something that has gone through a great deal of hard work.HTML5In this step, the previous history is shown in:

 

OldestCookiesNaturally, we all know that the problem is too small.4 kbAndIE6Only each domain name is supported20ItemsCookies, Too few. The advantage is that everyone supports it, and the support is quite good. Disabled long agoCookiesThe user does not exist, as if previously disabledJavascriptThe user does not exist.

 

Userdata Yes IE Junk. Which of the following statements is used most? Flash Right, the space is Cookie Of 25 Times, basically enough. Then Google Launched Gears , Although there are no restrictions, the unpleasant thing is to install additional plug-ins (no specific research ). Arrived HTML5 These are all unified. The official recommendation is for every website. 5 MB . If it is very large, it is enough to store some strings. What's strange is that all supported browsers currently use 5 MB Although some browsers can be set for users, the current situation is 5 MB It is more appropriate to consider.

Supported situations include,IEIn8.0It was quite unexpected. However, you must note that,IE,FirefoxDuring the test, you need to upload the file to the server (orLocalhost), Directly click the localHtmlFile.

 

First, check whether the browser supports local storage. InHTML5Local Storage isWindowAttributes, includingLocalstorageAndSessionstorageFrom the perspective of name, we can clearly identify the differences between the two. The former is always local, and the latter is only accompaniedSessionThe window is no longer displayed once it is closed. The two are used in the same way.LocalstorageFor example.

If (window. localstorage ){
Alert ('this browser supports localstore ');
} Else {
Alert ('this browser does not support localstore ');
}

 

To store data directlyWindow. localstorageAdd an attribute, for example:Window. localstorage.OrWindow. localstorage ["A"]. The method for reading, writing, and deleting data is simple. It exists as a key-value pair, as shown below:

Localstorage. A = 3 ;// Set A Is "3"
Localstorage ["A"] = "SFSF ";// Set A Is "SFSF" , Overwrite the above value
Localstorage. setitem ("B", "Isaac ");// Set B Is "Isaac"
VaR a1 = localstorage ["A"]; // Obtain A Value
VaR a2 = localstorage. ;// Obtain A Value
VaR B = localstorage. getitem ("B ");// Obtain B Value
Localstorage. removeitem ("C ");// Clear C Value

 

the most recommended method here is getitem () and setitem () , clear key-value pairs using removeitem () . To clear all key-value pairs at a time, you can use clear () . In addition, HTML5 A key () if you do not know which key values are available, use the following method:

VaR storage = Window. localstorage;
Function showstorage (){
For (VAR I = 0; I <storage. length; I ++ ){
// Key (I)Obtain the corresponding key, and then useGetitem ()Method to obtain the corresponding value
Document. Write (storage. Key (I) + ":" + storage. getitem (storage. Key (I) + "<br> ");
}
}

 

Write a simple counter that uses local storage:

VaR storage = Window. localstorage;
If (! Storage. getitem ("pageloadcount") storage. setitem ("pageloadcount", 0 );
Storage. pageloadcount = parseint (storage. getitem ("pageloadcount") + 1 ;//Required format conversion
Document. getelementbyidx_x ("count"). innerhtml = storage. pageloadcount;
Showstorage ();

As shown in:

 

Note that,HTML5Only strings can be stored in local storage. strings are automatically converted to strings when stored in any format. Therefore, you need to convert the data types when reading data. This is the last section.CodeMediumParseintThe reason for the use.

 

In additionIPhone/iPadSettingsSetitem ()There will be a strangeQuota_exceeded_errError.SetitemBefore, firstRemoveitem ()JustOK.

 

HTML5And providesStorageEvent. You can listen for changes to the key-value pair as follows:

If (window. addeventlistener ){
Window. addeventlistener ("Storage", handle_storage, false );
} Else if (window. attachevent ){
Window. attachevent ("onstorage", handle_storage );
}
Function handle_storage (e ){
If (! E) {e = Window. event ;}
// Showstorage ();
}

 

For event VariablesEIsStorageeventObject, provides some practical properties, you can observe the changes of key-value pairs, as shown in the following table:

Property

Type

Description

Key

String

The named key that was added, removed, or moddified

Oldvalue

Any

The previous value (now overwritten), or null if a new item was added

Newvalue

Any

The new value, or null if an item was added

URL/uri

String

The page that called the method that triggered this change

 

Add two key-value pairs hereAAndBAnd add a button. ToASet a fixed value. When you click the button, modifyBValue:

<Body>
<P> you have viewed this page <span id = "count"> 0 </span> time (s). </P>
<P> <input type = "button" value = "changestorage" onclick = "changes ()"/> </P>
<SCRIPT>
VaR storage = Window. localstorage;
If (! Storage. getitem ("pageloadcount") storage. setitem ("pageloadcount", 0 );
Storage. pageloadcount = parseint (storage. getitem ("pageloadcount") + 1 ;// Required format conversion
Document. getelementbyidx_x ("count"). innerhtml = storage. pageloadcount;
Showstorage ();
If (window. addeventlistener ){
Window. addeventlistener ("Storage", handle_storage, false );
} Else if (window. attachevent ){
Window. attachevent ("onstorage", handle_storage );
}
Function handle_storage (e ){
If (! E) {e = Window. event ;}
Showobject (E );
}
Function showobject (OBJ ){
// Recursive display Object
If (! OBJ) {return ;}
For (var I in OBJ ){
If (typeof (OBJ [I])! = "Object" | OBJ [I] = NULL ){
Document. Write (I + ":" + OBJ [I] + "<br/> ");
} Else {
Document. Write (I + ": object" + "<br/> ");
}
}
}
Storage. setitem ("A", 5 );
Function Changes (){
// Modify a key value to test Storage Event
If (! Storage. getitem ("B") {storage. setitem ("B", 0 );}
Storage. setitem ('B', parseint (storage. getitem ('B') + 1 );
}
Function showstorage (){
// Loop display Localstorage Key-value pairs in
For (VAR I = 0; I <storage. length; I ++ ){
// Key (I) Obtain the corresponding key, and then use Getitem () Method to obtain the corresponding value
Document. Write (storage. Key (I) + ":" + storage. getitem (storage. Key (I) + "<br> ");
}
}
</SCRIPT>
</Body>

 

The test shows that the browser currently does not support this function very well, onlyIPadAndFirefoxSupported, andFirefoxMessy support,EObjects do not have those attributes at all.IPadThe support is very good.E. Uri(NoE. url), On the desktopSafariNo, it's weird.

 

Currently, browsers all provide excellent developer debugging functions. The following areChromeAndFirefoxDebugging tool ViewLocalstorage:

In addition, currentlyJavascriptA lotJSONFormat. You can directly callJSON. stringify ()Convert it into a string. Called after readingJSON. parse ()Convert stringJSONFormat:

VaR details = {Author: "Isaac", "Description": "fresheggs", "rating": 100 };
Storage. setitem ("details", JSON. stringify (details ));
Details = JSON. parse (storage. getitem ("details "));

 

JSON Objects are supported Localstorage The browser is basically supported. Note that IE8 , It supports JSON But if the following compatible mode code is added, switch IE7 The Mode won't work. (This is still supported. Localstorage , Although Window. localstorage Yes [Object] Instead of the previous [Object Storage] But the test found Getitem () , Setitem () ).

<Meta content = "Ie = 7" http-equiv = "X-UA-compatible"/>

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.