1.創(chuàng)建broadcast channel的js文件:
class ChannelManager {
/**
* 創(chuàng)建頻道管理器
* @param {string} channelName - 頻道名稱(需保證同源頁(yè)面使用相同名稱)
* @param {object} [options] - 配置選項(xiàng)
* @param {boolean} [options.autoReconnect=true] - 是否自動(dòng)重連:ml-citation{ref="1,5" data="citationList"}
*/
constructor(channelName, options = {}) {
this.channelName = channelName;
this.options = { autoReconnect: true, ...options };
this._initChannel();
this._messageHandlers = new Set();
}
// 初始化頻道連接
_initChannel() {
this.channel = new BroadcastChannel(this.channelName);
// 消息監(jiān)聽
this.channel.onmessage = (event) => {
this._messageHandlers.forEach(handler => handler(event.data));
};
// 錯(cuò)誤處理:ml-citation{ref="1,3" data="citationList"}
this.channel.onmessageerror = (error) => {
console.error('消息解析失敗:', error);
this.close();
if (this.options.autoReconnect) this._initChannel();
};
this.channel.addEventListener('close', () => {
if (this.options.autoReconnect) this._initChannel();
});
}
/**
* 發(fā)送消息
* @param {any} data - 可序列化的任意類型數(shù)據(jù):ml-citation{ref="5" data="citationList"}
*/
send(data) {
if (this.channel) this.channel.postMessage(data);
}
/**
* 訂閱消息
* @param {function} handler - 消息處理函數(shù)
* @returns {function} 取消訂閱函數(shù)
*/
subscribe(handler) {
this._messageHandlers.add(handler);
return () => this.unsubscribe(handler);
}
// 取消訂閱
unsubscribe(handler) {
this._messageHandlers.delete(handler);
}
// 關(guān)閉頻道:ml-citation{ref="1,5" data="citationList"}
close() {
if (this.channel) {
this.channel.close();
this._messageHandlers.clear();
this.channel = null;
}
}
}
- 使用
// 創(chuàng)建頻道實(shí)例
const chatChannel = new ChannelManager('chat_room');
// 訂閱消息
const unsubscribe = chatChannel.subscribe(data => {
console.log('收到消息:', data);
});
// 發(fā)送消息
chatChannel.send({ user: 'Alice', text: 'Hello!' });
// 關(guān)閉頻道(切換頁(yè)面時(shí)建議調(diào)用)
chatChannel.close()
// window.addEventListener('beforeunload', () => chatChannel.close());
//vue: beforeDestory中調(diào)用chatChannel.unsubscribe 和chatChannel.close方法,react:useEffect(()=>{ return=>(調(diào)用chatChannel.unsubscribe 和chatChannel.close方法)},[])