防止用户在浏览器里重复打开页面

213 阅读1分钟

BroadcastChannel

Broadcast Channel API 可以实现同源下浏览器不同窗口、Tab 页、frame、iframe(通常是同一个网站下不同的页面) 之间的简单通讯。

本实现借助BroadcastChannel进行窗口或Tab页之间的通信,向已存在的channel通信,来判断自己(页面)是否已经存在。
页面打开时会向注册的channel发送window_opening的消息。浏览器内已打开的页面收到消息后也发送一个的消息window_existed。 如果新打开的窗口能收到window_existed消息,我们可以做一些交互(比如弹窗)提示用户当前页面已经存在,不要重复打开了。

(function onlyOnePage() {
  const messageType = {
    hello: 'window_opening',
    myself: 'window_existed',
  };
  const bc = new BroadcastChannel("page_same_notification");
  bc.addEventListener("message", (event) => {
    if (event.data === messageType.myself) {
      alert('已有页面打开,将为你自动关闭此页面');
      window.close();
      return;
    }
    if (event.data === messageType.hello) {
      bc.postMessage(messageType.myself);
    }
  });
  // 脚本加载后,向已经打开的网站页面发送广播
  bc.postMessage(messageType.hello);
}());