localstorage 更新監測 storage事件

一、存儲更新監測javascript

存儲狀態監測的原理是storage事件。storage事件說明:html

https://developer.mozilla.org/zh-CN/docs/Web/API/StorageEventjava

storage事件是註冊在window上的。ui

二、示例spa

同域下2個文件,分別爲test.html和test1.html。code

test.html文件爲:htm

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>storage事件</title>
    </head>

    <body>
        <script type="text/javascript"> setTimeout(function(){ window.localStorage.setItem('a', 2) },1000) window.addEventListener("storage", function(e) { console.log(e) }); </script>
    </body>

</html>

test1.html文件爲:blog

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>storage事件</title>
    </head>

    <body>
        <script type="text/javascript"> window.localStorage.setItem('a', 1) window.addEventListener("storage", function(e) { console.log(e) }); </script>
    </body>

</html>

運行2個文件,test1.html的控制檯輸出爲:事件

即能監測到localStorage的變化。ip

三、說明

(1)是同域的不一樣文件會監測到存儲值的變化。

(2)同一個文件,存儲值的變化,監測不到。如:

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>storage事件</title>
    </head>

    <body>
        <script type="text/javascript"> window.localStorage.setItem('a', 1) setTimeout(function(){ window.localStorage.setItem('a', 2) },2000) setTimeout(function(){ window.localStorage.setItem('a', 3) },3000) setTimeout(function(){ window.localStorage.setItem('a', 4) },4000) window.addEventListener("storage", function(e) { console.log(e) }); </script>
    </body>

</html>

運行上述文件,控制檯沒有輸出內容。

相關文章
相關標籤/搜索