页面通信
页面之间具有依赖关系
A页面通过window.open或iframe打开B页面后,A页面和B页面之间就有了依赖关系。有了依赖关系之后。发送方使用window.postMessage()向发送消息,接收方监听message事件接收消息。
<body>
Page A
<button onclick="openB()">打开b页面</button>
<button onclick="sendMsg()">发送消息</button>
</body>
<script>
let pageB = null
function openB() {
pageB = window.open('b.html')
}
function sendMsg() {
pageB.window.postMessage('Hello, I am pageA.')
}
window.addEventListener('message', e=>{
const { data, source } = e;
// A页面打开时会给自己发一个message事件
// 这个事件没有必要处理
if (source === window) {
return
}
console.log('data = ', data)
})
</script>
<body>
Page B
</body>
<script>
window.addEventListener('message', e=>{
const { data, source } = e;
// B页面打开时会给自己发一个message事件
// 如果不return掉,会陷入死循环
if (source === window) {
return
}
console.log('data = ', data)
source.window.postMessage('Hi, I am B.')
})
</script>
页面之间同源
这时可以通过对localStorage进行读写来实现通信(类似IPC的共享内存)。
/* 页面A */
function sendMsgByLocalStorage() {
localStorage.setItem("test", Math.random());
}
/* 页面B */
window.addEventListener("storage", (e) => {
if (e.key !== "test") {
return;
}
console.log("test is changed", localStorage.getItem("test"));
});
页面之间完全无关
引入一个bridge.html用于桥接:
- A和B分别通过iframe引入bridge.html,即可通过postMessage向该页面发送消息或接收消息。
- 两个bridge.html间通过localStorage进行通信。