zoukankan      html  css  js  c++  java
  • 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>

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

  • 相关阅读:
    PHP 小方法之 算生日
    PHP 小方法之 随机生成几位字符串
    PHP 小方法之 过滤参数
    PHP 小方法之 计算两个时间戳之间相差的日时分秒
    PHP 小方法之 仿百度蜘蛛采集
    PHP 小方法之 显示 今天 昨天 上周 上月 近三月 的时间
    PHP保留两位小数的几种方法
    mysql 常用命令(一)
    PHP数据库页面增删查
    PHP数据库登陆注册简单做法
  • 原文地址:https://www.cnblogs.com/mengfangui/p/10736317.html
Copyright © 2011-2022 走看看