使用window中storage实现两个页面简单交互

147 阅读1分钟

两个页面必须处于同源页面;每个页面的URL由协议、域名、端口和路径组成,如果他们的协议、域名、端口都相同时就属于同源。 第一个页面中写了三个不同按钮,分别注册事件当点击时给当前localStorage添加数据。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>red</button>
    <button>green</button>
    <button>blue</button>
    <script>
        bns=Array.from(document.querySelectorAll("button"));
        bns.forEach(item=>{
            item.addEventListener("click",clickHandler);
        })

        function clickHandler(e){

            localStorage.setItem('bgc',this.textContent);
        }
        </Script>
</body>
</html>

第二个页面中放一个div,侦听storage事件,当点击上一个页面的按钮时给这个div更换背景色。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
         div{
            width: 100px;
            height: 100px;
            background-color: brown;
        }
    </style>
</head>
<body>
    <div></div>
   <script>
       var div=document.querySelector("div");
       window.addEventListener("storage",storageHandler);

       function storageHandler(e){
           if(e.key==="bgc"){
               div.style.backgroundColor=e.newValue;
           }
       }
   </script>
</body>
</html>