美文网首页
不同页面/iframe间的通讯

不同页面/iframe间的通讯

作者: 李霖弢 | 来源:发表于2021-03-14 17:08 被阅读0次

同源通信

  1. 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);
};

  1. Web Worker / Service Worker / Shared Worker
    同源页面可以共用worker,借助worker作为桥梁可以互相通讯

  1. 通过监听storage事件
    storage事件只有在localstorage内容发生改变时触发,且页面自身不会触发自身的storage事件
//触发的页面
localStorage.a = 999;

//监听的页面
window.addEventListener('storage',function(e){
  console.log(e.key, e.oldValue, e.newValue);
});

  1. 通过任意共享存储
    localStoragesessionStorageIndexedDB等同源共享存储,再通过轮询或监听visibilitychange,查看数据是否发生变化

  1. 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");

  1. window.frames[iframe序号] + window.parent (仅对iframe有效)

非同源通信

  1. 页面A创建一个iframe,该iframe和页面B同源且能通过指定origin来忽略和A的同源限制,通过该iframe和页面B进行同源通信
  2. 通过服务器轮询/websocket通讯

相关文章

网友评论

      本文标题:不同页面/iframe间的通讯

      本文链接:https://www.haomeiwen.com/subject/idezqltx.html