HTML5 Localstorage Local Storage

Source: Internet
Author: User

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 Cookies are naturally known to all, the problem is mainly too small, probably also 4KB appearance, and IE6 only support each domain name There are too few cookies. 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 .

UserDatais aIEof things, rubbish. Now, the most used isFlashBar, Space isCookiesof the -times, basically enough. And after that,Googlelaunched aGears, although there is no limit, but the uncomfortable place is to install additional plug-ins (not specifically studied). to theHTML5to unify all this, the official recommendation is that every website5MB, very big, just save some strings, enough. What's weird is that all the supported browsers are currently using the5MB, although some browsers can be set for users, the current situation for web-makers is5MBto consider is more appropriate.



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

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 the name should be able to clearly identify the difference between 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;//Setato be"3"
Localstorage["a"] = "SFSF";//Setato be"SFSF", overriding the above values
Localstorage.setitem ("B", "Isaac");//Setbto be"Isaac"
var A1 = localstorage["a"];//Getathe value
var A2 = localstorage.a;//Getathe value
var B = Localstorage.getitem ("b");//Getbthe value
Localstorage.removeitem ("C");//ClearCthe value

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 quota_exceeded_err error when setting the iphone/ipad on the At this time generally before SetItem , first RemoveItem () on 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&nb sp;key that was added, removed, or moddified

&NBSP;OLDV Alue

 any

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

 newvalue

/ td>

 any

 the new value, or null if an item& nbsp;was added

 url/uri

 string

p> the page that called the method that 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 testStorageEvents
if (!storage.getitem ("B")) {Storage.setitem ("B", 0);}
Storage.setitem (' B ', parseint (Storage.getitem (' B ')) +1);
}
function Showstorage () {
//Loop DisplayLocalstoragethe key value pairs in the
for (Var i=0;i<storage.length;i++) {
Key (i)get the corresponding key, then useGetItem ()method to get 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 properties at all. IPad support is very good, with E.uri(not e.url), on the desktop Safari No, it's weird.

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



In addition, JavaScript currently uses very many JSON formats, and if you want to store them locally, you can call json.stringify () directly. convert it 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"));

Jsonobject in SupportLocalstorageBasic Support on the browser, it is important to note thatIE8, it supportsJSON, but if you add the following compatibility-mode code, cut toIE7mode is not available (this is still supportedLocalstorage, although the displayWindow.localstorageis a[Object], and not before the[Object Storage], but the test foundGetItem (),SetItem ()can be used, etc.).

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


HTML5 Localstorage Local Storage

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.