且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止同一个网站打开多个标签页?

更新时间:2023-02-16 14:28:20

我最近遇到了一个类似的问题,我不得不阻止在同一个 localStorage 上操作多个窗口/选项卡.

I recently ran across a similar problem where I had to prevent that multiple windows/tabs operated on the same localStorage.

解决方案是使用 StorageEvents:每个窗口每当另一个 (!) 窗口更改与此窗口使用的相同的 localStorage 时,都会收到一个 StorageEvent.

The solution was to use StorageEvents: every window receives a StorageEvent whenever another(!) window made changes to the same localStorage as this one uses.

因此,诀窍是为 localStorage 定义一个虚拟"键,并让每个窗口向该键写入一些随机值,以便让所有其他使用相同 localStorage 的窗口接收一个 StorageEvent:

Thus, the trick was to define a "dummy" key for localStorage and let every window write some random value into that key just to let all other windows using the same localStorage receive a StorageEvent:

  window.addEventListener('storage', () => {
    window.alert('another window or tab is working on the same localStorage')
  }, false)

  localStorage.setItem('Sentinel',Math.random())