Broadcastchannel-polyfill
兼容
快速上手
端内关闭相同页面,防止层级过深
import { useEffect } from "react";
import "broadcastchannel-polyfill";
import { Grounds } from "@ifeng/client_grounds";
export const useCloseSamePage = () => {
useEffect(() => {
// 端内环境下
if (window.grounds) {
// 获取无查询参数和哈希值的URL
const { origin, pathname } = window.location;
const currentUrl = `${origin}${pathname}`;
// 创建链接到命名频道的对象
const bc = new BroadcastChannel("bcCloseSamePage");
// 监听广播消息
bc.onmessage = (e) => {
const { data } = e;
const { url } = data;
if (url === currentUrl) {
Grounds.close();
}
};
bc.postMessage({ url: currentUrl });
}
}, []);
};
参考
BroadcastChannel 接口代理了一个命名频道,可以让指定 origin 下的任意 browsing context 来订阅它。它允许同源的不同浏览器窗口,Tab 页,frame 或者 iframe 下的不同文档之间相互通信。通过触发一个 message 事件,消息可以广播到所有监听了该频道的 BroadcastChannel 对象。