Detailed HTML5 Localstorage Local storage usage

Source: Internet
Author: User
Tags json key string string to json

When it comes to local storage, it's a great way to get to the HTML5, and the previous history is probably as shown in the following figure:

The earliest cookies naturally are known to all, the problem is too small, probably 4KB, and IE6 only support 20 cookies per domain, too little. The advantage is that we all support, but also good support. Long ago, those who had disabled cookies were slowly not there, as if they had previously disabled JavaScript.

UserData is IE's stuff, rubbish. Now use the most is Flash bar, space is a cookie 25 times times, basically enough. Then Google launched the gears, although there is no limit, but the uncomfortable place is to install additional plug-ins (no specific research). To the HTML5 all these are unified, the official suggestion is each website 5MB, very big, save some strings, enough. The more bizarre is that all supported browsers are currently using 5MB, although some browsers can let users set, but for Web page makers, the current situation on the 5MB to consider is more appropriate.

Supported by the picture above, ie at the time of 8.0 support, very unexpected. However, it is necessary to note that, IE, Firefox test when you need to upload files to the server (or localhost), directly point to open the local HTML file, is not.

The first thing is to detect whether the browser supports local storage. In HTML5, local storage is the property of a window, including Localstorage and Sessionstorage, from which the name should clearly identify the difference between the two, which is always local, and the latter is only accompanied by a session, and the window closes once it is closed. The use of the two is exactly the same, taking Localstorage as an example.

JavaScript code
if (window.localstorage) {
Alert (' This browser supports Localstorage ');
}else{
Alert (' This browser does not support Localstorage ');
}
The way to store data is to add an attribute directly to window.localstorage, such as: Window.localstorage.a or window.localstorage["a". Its read, write, delete operation method is very simple, is a key-value pairs of the way, as follows:

JavaScript code
Localstorage.a = 3;//Set A to "3"
Localstorage["a"] = "SFSF";/set A To "SFSF", overriding the value above
Localstorage.setitem ("B", "Isaac");/set B to "Isaac"
var A1 = localstorage["A"];//gets the value of a
var a2 = localstorage.a;//Gets the value of a
var B = Localstorage.getitem ("b");//Get the value of B
Localstorage.removeitem ("C");//clear value of C
The most recommended use here is GetItem () and SetItem (), clearing the key-value pairs using RemoveItem (). You can use clear () If you want all key-value pairs to be cleared at once. In addition, HTML5 provides a key () method that can be used without knowing what key values are available, as follows:

JavaScript code
var storage = Window.localstorage;
function Showstorage () {
for (Var i=0;i<storage.length;i++) {
Key (i) to obtain the corresponding keys, and then use the GetItem () method to obtain the corresponding value
document.write (Storage.key (i) + ":" + storage.getitem (Storage.key (i)) + "<br>");
}
}
Write one of the simplest, using local stored counters:

JavaScript code
var storage = Window.localstorage;
if (!storage.getitem ("Pageloadcount")) Storage.setitem ("Pageloadcount", 0);
Storage.pageloadcount = parseint (Storage.getitem ("Pageloadcount")) + 1;//must format conversion
Document.getelementbyidx_x ("Count"). InnerHTML = Storage.pageloadcount;
Showstorage ();
Keep refreshing to see the numbers rising a little, as shown in the following figure:

It should be noted that HTML5 local storage can only save strings, any format will be automatically converted to string when stored, so read, you need to do the type of conversion. This is why the parseint must be used in the previous code.

In addition, in Iphone/ipad sometimes set SetItem () will appear strange quota_exceeded_err error, then generally in SetItem before, first RemoveItem () ok.

HTML5 Local storage, also provides a storage event, you can monitor the change of key value pairs, using the following methods:

JavaScript code
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 variable E, it is a Storageevent object that provides some useful properties to observe the changes in key value pairs, such as the following table:

Property Type Description
Key String The named key that is added, removed, or moddified
OldValue any of the previous value (now overwritten), or null if a new item is added
NewValue any of the new value, or null if an item is added
Url/uri String The page that called the method so triggered this change

Here add two key values to A and B, and add a button. Set a fixed value for a, and modify the value of B when the button is clicked:

xml/html Code
<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;//must 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 the storage event
if (!storage.getitem ("B")) {Storage.setitem ("B", 0);}
Storage.setitem (' B ', parseint (Storage.getitem (' B ')) +1);
}
function Showstorage () {
Loop shows the key value pairs in the Localstorage
for (Var i=0;i<storage.length;i++) {
Key (i) to obtain the corresponding keys, and then use the GetItem () method to obtain the corresponding value
document.write (Storage.key (i) + ":" + storage.getitem (Storage.key (i)) + "<br>");
}
}
</script>
</body>
The test found that the current browser is not very good support for this, only the ipad and Firefox support, and Firefox support is messy, E object does not have those attributes. The ipad is very well supported, with E.uri (not e.url), Safari on the desktop, weird.

Browsers now have good developer debugging capabilities, and the following are the Chrome and Firefox debugging tools to view Localstorage:

In addition, currently JavaScript uses a lot of JSON format, and if you want to store it locally, you can call Json.stringify () directly to the string. When read out, call Json.parse () to convert the string to JSON format, as follows:

JavaScript code
var details = {Author: "Isaac", "description": "Fresheggs", "rating": 100};
Storage.setitem ("Details", json.stringify (Details));
Details = Json.parse (Storage.getitem ("Details"));

The JSON object is basically supported on browsers that support Localstorage, and it needs to be noted that IE8 supports JSON, but if you add the following compatibility mode code, it's not going to IE7 mode (still supports localstorage at this time, Although the display window.localstorage is [object], not the previous [object Storage], the test found that GetItem (), SetItem (), etc. can be used.

xml/html Code
<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.