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

东明兄 2019-01-27
0条评论 2,521 次浏览
东明兄 2019-01-270条评论 2,521 次浏览

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

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注