窗口通信?"/>
如何通过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实现跨源和跨窗口通信?
发布评论