• 如何通过postMessage实现跨源和跨窗口通信?


    一、语法

    otherWindow.postMessage(message, targetOrigin, [transfer]);

    • otherWindow:目标窗口(你想发送跨域消息的那个窗口),并非当前窗口
    • message:将要发送到其他 window 的数据
    • targetOrigin:通过窗口的 origin 属性来指定哪些窗口能接收到消息事件
    • transfer:可选参数,用的不多,可直接参考文档,此处忽略

    二、示例

    1、iframe和父窗口之间相互通信

    父窗口(http://127.0.0.1:5500/aaaaaaaaa.html)
    html部分

      <div>测试页面aaaaaaa</div>
      <iframe id="iframe" src="http://127.0.0.1:5501/bbbbb.html" width="1200" height="900"></iframe>
    
    • 1
    • 2

    js部分

      // 向iframe发送数据
      const iFrame = document.getElementById('iframe')
      iFrame.onload = () => {
        iFrame.contentWindow.postMessage('我是来自于父窗口的数据,可在iframe嵌入窗口中获取到', 'http://127.0.0.1:5501')
      }
    
      // 从iframe里获取数据
      window.addEventListener('message', e => {
        if (e.origin !== 'http://127.0.0.1:5501') return;
        console.log(e.data)
      }, false)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    子窗口(http://127.0.0.1:5501/bbbbb.html)
    js

    window.parent.postMessage('我是来自于子窗口的数据,可在父窗口中获取到','http://127.0.0.1:5500')
    window.addEventListener('message',e=>{
      if(e.origin !== 'http://127.0.0.1:5500') return;
       console.log(e.data)
    },false)
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1、不同窗口之间相互通信

    窗口一(http://127.0.0.1:5500)
    html部分

    <button onclick='onTest()'>测试页面aaaaaaa</button>
    
    • 1

    js部分

     const targetWindow = window.open('http://127.0.0.1:5501/bbbbb.html');
      function onTest() {
        // 接收消息
        window.addEventListener('message', (e) => {
          if (e.origin !== "http://127.0.0.1:5501") return;
          console.log(e.data, e)
        })
        // 先判断5501窗口是否已被关闭
        if (targetWindow.closed) {
          const targetWindow = window.open('http://127.0.0.1:5501/bbbbb.html');
        }
        // 发送消息
        setTimeout(() => {
          targetWindow.postMessage('来自窗口5500的数据', 'http://127.0.0.1:5501')
        }, 3000)
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    窗口二(http://127.0.0.1:5501)

    window.addEventListener('message', (e) => {
      if (e.origin !== "http://127.0.0.1:5500") return;
       console.log(e.data, e)
       e.source.postMessage('来自5501的数据', e.origin)
     })
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    阿里P8架构师都在学习参考的SpringCloud微服务实战文档
    ssh秘钥和python 虚拟环境
    固定时间刷新算法
    服务器硬件介绍(2)
    第五章 目标检测中K-means聚类生成Anchor box(工具)
    labview中循环停止事件的深入研究
    STN:不规则文本矫正网络的探索
    基于python的电影爬虫可视化系统设计与实现
    函数的声明和定义——C语言初阶
    仿QQ音乐(HTML+CSS)
  • 原文地址:https://blog.csdn.net/qq_38990451/article/details/133945568