前端跨页面通信 Broadcast Channel 与 window.postMessage

BroadcastChannel,叫做“广播频道”,官方文档说,该API是用于同源不同页面之间完成通信的功能。

与window.postMessage的区别:BroadcastChannel只能用于同源的页面之间进行通信,而window.postMessage却可以用于任何的页面之间,

基于BroadcastChannel的同源策略,它无法完成跨域的数据传输,跨域的情况,我们还是使用window.postMessage来处理

使用起来很简单:

发送消息:

var bc = new BroadcastChannel(‘test_channel’);

bc.postMessage(‘hello world’);

接收消息:

bc.onmessage = function(msg){
    
console.log(msg);
}

参考文档:

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

https://developer.mozilla.org/zh-CN/docs/Web/API/Broadcast_Channel_API

上一篇 解决 Cannot download "https://github.com/sass/node-sass/releases/download/binding.node的问题
下一篇 Angular + Rxjs 获取 Response header