封裝broadcastchannel,支持跨標(biāo)簽通信、多訂閱模式、自動(dòng)重連和錯(cuò)誤處理

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;
    }
  }
}

  1. 使用
// 創(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方法)},[])
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容