Skip to content

BroadcastChannel Api

作用:跨标签页通信

BroadcastChannel允许同源的不同浏览器窗口,Tab 页,frame 或者 iframe 下的不同文档之间相互通信。通过触发一个 message 事件,消息可以广播到所有监听了该频道的 BroadcastChannel 对象。

1.构造函数

需要传入一个字符串作为标识符,相当于广播名,可通过实例对象的name属性获取

js
const channel = new BroadcastChannel("demo");

console.log(channel.name)   // demo

2.发送数据

通过实例对象的postmessage方法发送任意类型的数据

js
const channel = new BroadcastChannel("demo");

channel.postMessage('你好');

3.关闭连接

通过调用 BroadcastChannel.close() 方法,可以马上断开其与对应频道的关联,并让其被垃圾回收。这是必要的步骤,因为浏览器没有其他方式知道频道不再被需要。

js
const channel = new BroadcastChannel("demo");

channel.close();

4.监听广播

通过监听实例对象的message事件,可获取广播发送的数据

通过事件对象e.data获取数据

js
const channel = new BroadcastChannel("demo");

channel.addEventListener("message", (e) => {
    console.log(e.data);
});

5.监听错误

当频道收到一条无法反序列化的消息时会在 BroadcastChannel 对象上触发 messageerror 事件。

js
channel.addEventListener('messageerror', (event) => {
  console.error(event);
});

6.封装广播工具

channel.js

js
// 实例化广播对象
const channel = new BroadcastChannel("demo");

// 发送广播
/**
 *
 * @param {string} type 描述信息的类型
 * @param {any} content 发送的数据
 */
const sendMsg = (type, content) => {
    channel.postMessage({
        type,
        content,
    });
};

//接收广播
/**
 *
 * @param {function} callback 处理接收数据的回调
 * @returns 移除监听
 */
const listenMsg = (callback) => {
    const handler = (e) => {
        callback && callback(e.data);
    };
    channel.addEventListener("message", handler);
    return () => {
        channel.removeEventListener("message", handler);
    };
};

MIT Licensed