localstorage 更新監測 storage事件


1、存儲更新監測

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

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

storage事件是注冊在window上的。

2、示例

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

test.html文件為:

<!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文件為:

<!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的變化。

3、說明

(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>

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM