同源跨页面通信

2019-04-02  本文已影响0人  人穷脸丑小前端

同源跨页面通信小记

BroadcastChannel

The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.

BroadcastChannel接口表示指定源的任何浏览上下文可以订阅的命名通道。它允许相同来源的不同文档(在不同的窗口,选项卡,框架或iframe中)之间的通信。通过在监听频道的所有对象上触发的事件来广播消息。

BroadcastChannel()接收一个参数name,即通道名称。页面可以有多个通道,需要用name区分。
BroadcastChannel实例可以调用postMessage就可以发送消息(参数可以是任何类型)。
通过对BroadcastChannel实例添加message事件就可以接收消息。

<div id="text-box"></div>
<button id="submit-text">发送消息</button>
<script>

  const bc=new BroadcastChannel('kevin');
  const textBox=document.querySelector('#text-box');
  const btn=document.querySelector('#submit-text');
  bc.addEventListener('message',(e)=>{
      textBox.innerHTML=e.data;
  });
  btn.addEventListener('click',()=>{
      bc.postMessage('消息来了'+(+new Date()));
  })


</script>

那么在不同的窗口,选项卡,框架或iframe中。有一个页面发出广播,其他页面都会收到消息(发消息的页面不会触发受到消息事件)

上一篇 下一篇

猜你喜欢

热点阅读