taoliujun / blog

https://taoliujun.github.io/blog/
https://taoliujun.github.io/blog/
0 stars 0 forks source link

Web API - Broadcast Channel #59

Open taoliujun opened 4 months ago

taoliujun commented 4 months ago

Broadcast Channel

MDN: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

Broadcast Channel可以在同源情况下,在一种浏览器的不同窗口、标签页、frame中简单通信。

接口

BroadcastChannel

传入频道名称,返回实例,包含了message事件来监听消息、postMessage方法来发送信息。

示例

示例:https://taoliujun.github.io/example/web-api/Broadcast_Channel_API/index.html

  1. 打开两个Chrome窗口,查看日志:

image

taoliujun commented 4 months ago

web api的跨页通信标准有好几个,Broadcast Channel是其中较为明确和简单的一个。在多页web中很有用,比如通知所有页面退出登录。