美文网首页
跨页面标签页通讯 - BroadcastChannel

跨页面标签页通讯 - BroadcastChannel

作者: Coldhands | 来源:发表于2024-04-17 23:20 被阅读0次
const channel = new BroadcastChannel("sync-refresh");

/**
 * @param { "refresh" } type
 * @param { any } msg
 */
export function sendMsg(type: string, msg: any = "") {
  channel.postMessage({
    type,
    msg
  });
}

export function listenMsg(callback: any) {
  const handler = (e: any) => {
    callback && callback(e.data);
  };
  channel.addEventListener("message", handler);
  return () => {
    channel.removeEventListener("message", handler);
  };
}

// 使用方法
// listenMsg((info) => {
//   info.type
//   info.msg
// })

// 监听登录刷新页面
const unListen = listenMsg((info: any) => {
  // todo
});

// 取消监听
onUnmounted(unListen);

相关文章

网友评论

      本文标题:跨页面标签页通讯 - BroadcastChannel

      本文链接:https://www.haomeiwen.com/subject/wvyexjtx.html