页签通信方式

143 阅读1分钟

1、BroadcastChannel

MDN: developer.mozilla.org/zh-CN/docs/…

  • 简单用法:
/** 页面A  创建频道*/
let channel = new BroadcastChannel(name);
channel.postMessage("发送的消息");

/** 页面B 订阅频道*/
channel.onmessage = (value) => {
    //value - "发送的消息"
}
/** 关闭频道 */
channel.close();
  • 优点:使用简单方便,用于两个页面简单的消息通讯
  • 缺点:IE safari 不支持

2、window.postMessage

MDN: developer.mozilla.org/zh-CN/docs/…

  • 简单用法
/** 页面A,发送消息 */
let popup = window.open('页面B地址');
let message = "发送的消息";
let targetOrigin = "指定接收消息的页面,其值可以是字符串"*"(表示无限制)或者一个URI";
let transfer = "是一串和message 同时传递的 [`Transferable`](https://developer.mozilla.org/zh-CN/docs/Web/API/Transferable) 对象. 这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。"

popup.postMessage(message, targetOrigin, [transfer]);

/** 页面B, 接收消息 */
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
  let origin = event.origin; 发送方的地址(安全验证)
  let data = event.data; //接收的消息
}
  • 优点: 能进行页面直接的通讯
  • 缺点: 只能单选通讯

3、window.onstorage

描述:利用浏览器缓存 localStorage 的特性进行页面间通讯

  • 简单用法
/** 页面A,进行发消息 */
window.localStorage.setItem('info', JSON.stringify({
    status: 'success'
}));

/** 页面B, 接收消息 */
window.onstorage = function (event) {
  if (event.key === 'info') {
    let info = window.localStorage.getItem(event.key); //接收到的消息
    window.localStorage.removeItem(event.key);
  }
}
  • 优点: 能进行一对多的通讯
  • 缺点: 由于利用 localStorage ,所以只能在同协议同域名同端口号下通讯