Localstorage details (the difference from sessionstorage)

Source: Internet
Author: User
Tags sessionstorage

Basic usage of localstorage on HTML5

1. Get the length of the Localstorage: window.localStorage.length

2. Add/Edit contents of Localstorage: Window.localStorage.setItem (key, value);

3. Obtain the value of the key corresponding to the localstorage according to the corresponding index: Window.localStorage.key (index);

4. Obtain the corresponding Value:window.localStorage.getItem (key) according to the corresponding key;

HTML5 Localstorage Local Storage

When it comes to local storage, it's been a long walk to HTML5, and the previous history probably looks like this:

The earliest cookies are naturally known, the problem is mainly too small, probably also 4KB appearance, and IE6 only support each domain name 20 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, space is 25 times times the cookie, 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 the situation as above, ie in 8.0 when the support, very unexpected. However, it is important to note that IE, 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 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;//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 the figure below:

It is important to note that HTML5 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, on the Iphone/ipad sometimes set SetItem () will appear strange quota_exceeded_err error, then generally before SetItem, first RemoveItem () 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:

 any

 property

 type

 description

 key

 string

 the named key&nb sp;that was added, removed, or moddified

 oldvalue

/td>

 any

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

 newvalue

 The new value, or null if an item  was added

 url/uri

 string

&N Bsp 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 be formatted for 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 of 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 () {
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:

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.