storage事件 js页面间通信

1、概述

https://developer.mozilla.org/en-US/docs/Web/Events/storage

localStorage 或者sessionStorage存储的数据发生时会触发storage事件。

2、示例

示例中会展示所有的storage事件属性值。

 

A文件:

<!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>Document</title>
    </head>

    <body>
        <script type="text/javascript">
            window.addEventListener("storage", function(e) {
                //事件目标 输出:[object Window]对象(因为绑定在window上)
                console.log("target: "+e.target);
                //事件类型 输出:storage
                console.log("type : "+e.type);
                //事件是否冒泡 输出:false
                console.log("bubbles : "+e.bubbles);
                //事件是否可撤销 输出:false
                console.log("tarcancelable: "+e.cancelable);
                //键名
                console.log("key: "+e.key);
                //键值原值
                console.log("oldValue: "+e.oldValue);
                //键值新值
                console.log("newValue: "+e.newValue);
                //触发事件的url
                console.log("url: "+e.url);
                //受影响的存储空间 输出[object Storage]
                console.log("storageArea: "+e.storageArea);
            });
        </script>
    </body>

</html>

 

B文件:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>

    <body>
        <script type="text/javascript">
            localStorage.clear();
            localStorage.setItem('foo', 'bar');
        </script>
    </body>

</html>

操作:先打开A页面,后打开B页面。

B页面控制台输入:

storage事件效果:

 

原文地址:https://www.cnblogs.com/mengfangui/p/8664074.html