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

编程入门 行业动态 更新时间:2024-10-09 03:28:43

如何通过postMessage实现跨源和跨<a href=https://www.elefans.com/category/jswz/34/1771087.html style=窗口通信?"/>

如何通过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>

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)

子窗口(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、不同窗口之间相互通信

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

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

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)}

窗口二(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)})

更多推荐

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

本文发布于:2023-12-06 07:09:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1666818.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:窗口   通信   postMessage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!