同源通信
- BroadcastChannel (IE11不支持)
BroadcastChannel 代理了一个命名频道,允许同源的页面或 iframe之间相互通信。通过触发一个 message 事件,消息可以广播到所有监听了该频道的 BroadcastChannel 对象。
//发送消息的页面
const bc = new BroadcastChannel('my_channel_name');
bc.postMessage("hello world");
//接收消息的页面
const bc = new BroadcastChannel('my_channel_name');
bc.onmessage = function (e) {
console.log(`[${e.currentTarget.name}] receive message:`, e.data);
};
- Web Worker / Service Worker / Shared Worker
同源页面可以共用worker,借助worker作为桥梁可以互相通讯
- 通过监听
storage
事件
storage
事件只有在localstorage
内容发生改变时触发,且页面自身不会触发自身的storage
事件
//触发的页面
localStorage.a = 999;
//监听的页面
window.addEventListener('storage',function(e){
console.log(e.key, e.oldValue, e.newValue);
});
- 通过任意共享存储
如localStorage
、sessionStorage
、IndexedDB
等同源共享存储,再通过轮询或监听visibilitychange
,查看数据是否发生变化
- window.open + window.opener(仅对页面有效)
期间也可以通过postmessage
通信
//parent
var childPage = window.open("./child.html");
if(!childPage .closed){
childPage.alert("hello world");
}
//child
var parentPage = window.opener;
parentPage.alert("hello world");
- window.frames[iframe序号] + window.parent (仅对iframe有效)
非同源通信
- 页面A创建一个iframe,该iframe和页面B同源且能通过指定
origin
来忽略和A的同源限制,通过该iframe和页面B进行同源通信
- 通过服务器轮询/websocket通讯
网友评论