otherWindow.postMessage(message, targetOrigin, [transfer]);
父窗口(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)
窗口一(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)
})