zoukankan      html  css  js  c++  java
  • js页面间通信方法实现

      在写页面的时候经常会碰到这样的需求:需要两个打开着的页面间传递数据或者事件。

      比如:已有列表页A,通过A打开详情B进行编辑;编辑保存之后希望A能自动刷新页面。这个时候就可以用到“storage”事件。关于localStorage的用法可在其他地方找到。

      可触发“storage”事件的条件如下:

      同一个浏览器打开了多个同源的页面(URL由协议、域名、端口和路径组成,如果两个URL的协议、域名和端口相同,则表示他们同源);

      一个网页中修改localStorage

      另一个网页注册了storage事件

    http://www.cnblogs.cn/demo/index.html
    
    //这个网址,协议是http://域名是www.cnblogs.cn,端口是80(默认端口可以省略)
    
    
    //对比URL:
    
    http://www.cnblogs.cn/demo2/other.html     //同源
    
    http://www.cnblogs.cn:81/demo/index.html   //不同源
    
    http://sxh.cnblogs.cn/demo/index.html      //不同源
    
    http://www.pudn.cn/demo/index.html         //不同源

      在测试的时候,一定要保证是同源页面。

      下面是页面间交互代码,实现非常简单,pageA和pageB之间通信。

    pageA:添加“storage”监听

    <!DOCTYPE html>
    
    <html>
    
    <head>
    
        <title>page A</title>
    
    </head>
    
    <body>
    
    <script>
    
        window.addEventListener("storage", function (e) {
    
            console.log(e)
    
            console.log(e.newValue)
    
        });
    
    </script>
    
    </body>
    
    </html>

    pageB:设置localStorage

    <!DOCTYPE html>
    
    <html>
    
    <head>
    
    <title>page B</title>
    
    </head>
    
    <body>
    
    <button>click<button>
    
    </body>
    
    <script>
    
          document.querySelector('button').onclick = function(){
            //留意random,若Refresh的值未做变更,则不会触发A页面的“storage”事件
                  localStorage.setItem('Refresh', Math.random()*10);
    
          }
    
    </script>
    
    </html>

      

  • 相关阅读:
    BeautifulSoup
    requests
    安装xpath helper
    取消搜狗输入法的快捷键
    numpy初识 old
    Jupyter Notebook 快捷键
    安装numpy、matplotlib
    JavaScript 继承 -JavaScript高级程序设计
    mac /windows
    unicode 地址
  • 原文地址:https://www.cnblogs.com/zran/p/11428158.html
Copyright © 2011-2022 走看看