Home  >  Article  >  Web Front-end  >  Detailed explanation of local storage usage of H5’s LocalStorage

Detailed explanation of local storage usage of H5’s LocalStorage

php中世界最好的语言
php中世界最好的语言Original
2018-03-27 09:20:302793browse

This time I will bring you a detailed explanation of the use of H5's LocalStorage local storage. What are the precautions when using LocalStorage local storage? Here are practical cases, let's take a look.

Speaking of local storage, this thing has really gone through a lot of hard work to get to the point of HTML5. The previous history is roughly as shown in the figure below:


Everyone knows about the earliest Cookies. The main problem is that they are too small, about 4KB, and IE6 only supports 20 cookies per domain name, which is too few. The advantage is that everyone supports it, and the support is quite good. Those users who disabled cookies a long time ago have gradually disappeared, just like the users who disabled javascript in the past no longer exist.

userData is something from IE, garbage. The most commonly used one now is Flash. The space is 25 times that of Cookie, which is basically enough. Then Google launched Gears. Although there are no restrictions, the unpleasant part is that additional plug-ins must be installed (I have not studied it in detail). With HTML5, these have been unified. The official recommendation is 5MB for each website, which is very large. Just save some strings, which is enough. What is strange is that all supported browsers currently use 5MB. Although some browsers allow users to set it, for web page creators, it is more appropriate to consider 5MB in the current situation.


The support situation is as shown above. IE has supported it since 8.0, which is very unexpected. However, it should be noted that when testing IE and Firefox, you need to upload the file to the server (or localhost). Directly clicking on the local HTML file will not work.

The first thing is to check whether the browser supports local storage. In HTML5, local storage is a window attribute, including localStorage and

sessionStorage. You can clearly identify the difference between the two from their names. The former always exists locally, while the latter only accompanies the session. , the window disappears once it is closed. The usage of the two is exactly the same. Here we take localStorage as an example.

if(window.localStorage){
 alert('This browser supports localStorage');
}else{
 alert('This browser does NOT support localStorage');
}
The way to store data is to directly add a property to window.localStorage, such as: window.localStorage.a or window.localStorage["a"]. Its reading, writing, and deletion operation methods are very simple and exist in the form of key-value pairs, as follows:

localStorage.a = 3;//设置a为"3"
localStorage["a"] = "sfsf";//设置a为"sfsf",覆盖上面的值
localStorage.setItem("b","isaac");//设置b为"isaac"
var a1 = localStorage["a"];//获取a的值
var a2 = localStorage.a;//获取a的值
var b = localStorage.getItem("b");//获取b的值
localStorage.removeItem("c");//清除c的值
The most recommended ones here are naturally getItem() and setItem() to clear the key value Use removeItem() on . If you want to clear all key-value pairs at once, you can use clear(). In addition, HTML5 also provides a key() method, which can be used when you don’t know what key values ​​there are, as follows:

var storage = window.localStorage;
function showStorage(){
 for(var i=0;i2fbbdc9c3515a3c578e5eb88e1f5a546");
 }
}
Write the simplest counter that uses local storage:

var storage = window.localStorage;
if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换
document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount;
showStorage();
Keep refreshing and you will see the number rising little by little, as shown in the figure below:


It should be noted that HTML5 local storage can only store strings , any format will be automatically converted to a string when stored, so when reading, you need to perform type conversion yourself. This is why parseInt must be used in the previous code.

In addition, sometimes a strange QUOTA_EXCEEDED_ERR error occurs when setting setItem() on iPhone/iPad. In this case, removeItem() is usually OK before settingItem.

HTML5’s local storage also provides a storage event, which can monitor changes in key-value pairs. The usage method is 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 the event variable e, it is a StorageEvent object, providing With some practical attributes, you can observe the changes of key-value pairs very well, 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

这里添加两个键值对a和b,并增加一个按钮。给a设置固定的值,当点击按钮时,修改b的值:

6c04bd5ca3fcae76e30b72ad730ca86d
e388a4556c0f65e1904146cc1a846beeYou have viewed this page d7095a27822ebfc9324399e7e2aaea81054bdf357c58b8a65c66d7c19c8e4d114  time(s).94b3e26ee717c64999d7867364b1b4a3
e388a4556c0f65e1904146cc1a846bee01d8bff6816d3fe04eb5c6a227498a5994b3e26ee717c64999d7867364b1b4a3
3f1c4e4b6b16bbbd69b2ee476dc4f83a
var storage = window.localStorage;
if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换
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){
 //递归显示object
 if(!obj){return;}
 for(var i in obj){
  if(typeof(obj[i])!="object" || obj[i]==null){
   document.write(i + " : " + obj[i] + "076402276aae5dbec7f672f8f4e5cc81");
  }else{
   document.write(i + " : object" + "076402276aae5dbec7f672f8f4e5cc81");
  }
 }
}
storage.setItem("a",5);
function changeS(){
 //修改一个键值,测试storage事件
 if(!storage.getItem("b")){storage.setItem("b",0);}
 storage.setItem('b',parseInt(storage.getItem('b'))+1);
}
function showStorage(){
 //循环显示localStorage里的键值对
 for(var i=0;i2fbbdc9c3515a3c578e5eb88e1f5a546");
 }
}
2cacc6d41bbb37262a98f745aa00fbf0
36cc49f0c466276486e50c850b7e4956

测试发现,目前浏览器对这个支持不太好,仅iPad和Firefox支持,而且Firefox支持得乱糟糟,e对象根本没有那些属性。iPad支持非常好,用的是e.uri(不是e.url),台式机上的Safari不行,诡异。

目前浏览器都带有很好的开发者调试功能,下面分别是Chrome和Firefox的调试工具查看LocalStorage:


 


 

另外,目前javascript使用非常多的json格式,如果希望存储在本地,可以直接调用JSON.stringify()将其转为字符串。读取出来后调用JSON.parse()将字符串转为json格式,如下所示:

var details = {author:"isaac","description":"fresheggs","rating":100};
storage.setItem("details",JSON.stringify(details));
details = JSON.parse(storage.getItem("details"));


 

JSON对象在支持localStorage的浏览器上基本都支持,需要注意的是IE8,它支持JSON,但如果添加了如下的兼容模式代码,切到IE7模式就不行了(此时依然支持localStorage,虽然显示window.localStorage是[object],而不是之前的[object Storage],但测试发现getItem()、setItem()等均能使用)。

<meta content="IE=7" http-equiv="X-UA-Compatible"/>

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

<a href="//m.sbmmt.com/html5-tutorial-390148.html" target="_blank">基于HTML5陀螺仪实现移动动画效果</a><br>怎样用H5计算手机摇动次数

The above is the detailed content of Detailed explanation of local storage usage of H5’s LocalStorage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn