1. 程式人生 > >h5 storage事件監聽

h5 storage事件監聽

分析

引用《h5移動web開發指南》上的話:

“當同源頁面的某個頁面修改了localStorage,其餘的同源頁面只要註冊了storage事件,就會觸發”

所以,localStorage的例子執行需要如下條件:

  • 同一瀏覽器打開了兩個同源頁面
  • 其中一個網頁修改了localStorage
  • 另一網頁註冊了storage事件

很容易犯的錯誤是,在同一個網頁修改本地儲存,又在同一個網頁監聽,這樣是沒有效果的。

例子

網頁A:監聽了storage事件:

<!DOCTYPE html>
<html>
<head lang="en">
    <title>A</title>
</head>
<body>
<script>
    window.addEventListener("storage", function (e) {
        alert(e.newValue);
    });
</script>
</body>
</html>

網頁B:修改了localStorage

<!DOCTYPE html>
<html>
<head lang="en">
    <title>B</title>
</head>
<body>
<script>
    localStorage.clear();
    localStorage.setItem('foo', 'bar');
</script>
</body>
</html>

執行 : 將上面兩個網頁儲存,放到同一個伺服器上,然後,先開啟A.html,再開啟B.html。就會看到A.html會彈出提示框。注意兩個網頁要同源。

擴充套件

如果非得要在同一網頁監聽怎麼辦?可以重寫localStorage的方法,丟擲自定義事件:

<!DOCTYPE html>
<html>
<head lang="en">
    <title>A</title>
</head>
<body>
<script>
    var orignalSetItem = localStorage.setItem;
    localStorage.setItem = function(key,newValue){
        var setItemEvent = new Event("setItemEvent");
        setItemEvent.newValue = newValue;
        window.dispatchEvent(setItemEvent);
        orignalSetItem.apply(this,arguments);
    }
    window.addEventListener("setItemEvent", function (e) {
        alert(e.newValue);
    });
    localStorage.setItem("nm","1234");
</script>
</body>
</html>