1、存储更新监测

存储状态监测的原理是storage事件。storage事件说明:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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 更新监测 storage事件 随笔

即能监测到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>

运行上述文件,控制台没有输出内容。

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄