Skip to content
0

Broadcast Channel

适用于处于同一浏览器下,多个同源页面的通信

原理

多个页面,通过 new BroadcastChannel 方法,传入同一个标识符

undefined
undefined

加入同一个 Channel 后,其中一个页面可以向其他页面广播消息,其他页面监听 message 事件,接收信息

例子

<script>
const bc = new BroadcastChannel('fe-book')

bc.postMessage('New Message')
</script>
<script>
const bc = new BroadcastChannel('fe-book')

bc.onmessage = e => {
  console.log(e.data) //=> 'New Message'
}
</script>

心跳包检测

确保两个窗口都保持活跃,可以定时发送消息和确认消息。下面是一个简单的例子,页面双方都需要执行下面的代码:

let lastReceiverHeartbeatTime = Date.now()

// listen
const bc = new BroadcastChannel('fe-book')

bc.onmessage = (event) => {
  lastReceiverHeartbeatTime = Date.now()
  console.log(`Received heartbeat at ${event.data.timestamp}`);
}

// checker
setInterval(() => {
  if(Date.now() - lastReceiverHeartbeatTime > 5000) {
    console.error('Disconnected')
  }
}, 1000)

// send
setInterval(() => {
  bc.postMessage({
    type: 'heartbeat',
    timestamp: Date.now()
  })
}, 1000)

Released under the MIT License.