Html 5 Localstorage

Source: Internet
Author: User

HTML5 Localstorage Local Storage

HTML5 Localstorage Local Storage

When it comes to local storage, it's been a long walk to HTML5 , and the previous history is probably as follows:

The earliest cookie is naturally known to all, the problem is mainly too small, probably also 4KB appearance, and IE6 only support each domain name of the three Cookies, too few. The advantage is that we all support, but also very good support. Users who had previously disabled cookies were also slow to exist, as if the user had not already disabled JavaScript .

UserData is a thing of IE, rubbish. Now the most used is the Flash Bar, the space is a Cookie of the times, basic enough. Then Google introduced the Gears, although there is no limit, but the uncomfortable place is to install additional plug-ins (not specifically studied). To the HTML5 to unify these all, the official suggestion is each website 5MB, very big, save some string, enough. The weird thing is that all supported browsers currently use 5MB, although some browsers can let users set up, but for the web maker, the current situation on 5MB to consider is more appropriate.



Support for the situation,IE in the 8.0 when the support, very unexpected. However, it is important to note thatIE,Firefox testing needs to upload files to the server (or localhost), directly open the local HTML file, is not possible.

First, it is natural to detect whether the browser supports local storage. In HTML5 , local storage is a window property, including Localstorage and Sessionstorage, from which thename should clearly identify the difference between the two, The former is always local, the latter is only accompanied by the session, the window once closed is gone. The use of the two is exactly the same, for example, Localstorage.

if (window.localstorage) {
Alert (' This browser supports Localstorage ');
}else{
Alert (' This browser does not support Localstorage ');
}

The way to store data is to add a property directly to Window.localstorage, for example:window.localstorage.a or window.localstorage[" A "]. Its read, write, delete operation method is very simple, is in the way of key-value pairs exist, as follows:

Localstorage.a = 3;// set a to "3"
Localstorage["a"] = "SFSF";// set a to "SFSF", overriding the above value
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");/ / clears the value of C

The most recommended use here is GetItem () and SetItem (), clearing the key value pairs using removeitem (). If you want to clear all key-value pairs at once, you can use clear (). In addition,HTML5 also provides a key () method that can be used when you do not know what key values are available, as follows:

var storage = Window.localstorage;
function Showstorage () {
for (Var i=0;i<storage.length;i++) {
Key (i) obtains the corresponding key, then uses 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 locally stored counters:

var storage = Window.localstorage;
if (!storage.getitem ("Pageloadcount")) Storage.setitem ("Pageloadcount", 0);
Storage.pageloadcount = parseint (Storage.getitem ("Pageloadcount") + 1;// must be formatted for conversion
Document.getelementbyidx_x ("Count"). InnerHTML = Storage.pageloadcount;
Showstorage ();

Keep on refreshing to see the numbers rise a little bit, as shown in:

It is important to note thatHTML5 Local storage can only store strings, and any format stored will be automatically converted to strings, so when reading, you need to do a type of conversion. This is why parseint must be used in the previous code .

In addition, SetItem () is sometimes a strange quota_exceeded_err error when set on Iphone/ipad, which is usually preceded by SetItem . RemoveItem () is OK .

HTML5 's local storage also provides a storage event that can be used to listen for changes to key-value pairs, using the following method:

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 the event variable e, is a storageevent object, provides some useful properties, can be very good to observe the changes in key value pairs, such as the following table:

Property

Type

Description

Key

String

The named key is added, removed, or moddified

OldValue

Any

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

NewValue

Any

The new value, or null if an item is added

Url/uri

String

The page that called the method, the 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:

<body>
<p>you has 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 displayObject
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 () {
cyclic display of key-value pairs in Localstorage
for (Var i=0;i<storage.length;i++) {
Key (i) obtains the corresponding key, then uses 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 iPad and Firefox support, and Firefox support is messy,e objects do not have those attributes. IPad Support is very good, with E.uri(not e.url), Safari on the desktop is not, weird.

Currently the browser has a good developer debugging capabilities, the following are Chrome and Firefox Debugging tools to view localstorage:



In addition, currently JavaScript uses a very rich json format, and if you want to store it locally, you can call Json.stringify () to convert it directly to a string. After reading it , call Json.parse () to convert the string to JSON format, as follows:

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

JSON objects are basically supported on browsers that support Localstorage, and it is important to note that IE8supports json, but if you add the following compatibility-mode code, cut to IE7  Mode is not available ( Localstorage is still supported, although the display window.localstorage is [object], not the previous [object Storage], but the test found GetItem (),SetItem (), etc. can be used).

<meta content= "ie=7" http-equiv= "x-ua-compatible"/>

Html 5 Localstorage

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.