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