繁体   English   中英

管理窗口、浏览器选项卡之间的计时器。 本地存储事件

[英]Manage timer between windows, browser tabs. localStorage events

我正在寻找一种如何在浏览器中的多个选项卡或窗口之间进行通信的方法(在同一个域上,而不是 CORS)。

我正在使用计时器,它应该适用于所有网站页面。 如果有办法同时在所有页面(新窗口)上停止/暂停/播放计时器?

例如,我有 2 个选项卡 - 第 1 页和第 2 页...在两个页面上我都运行相同的计时器。 如果我在第 1 页单击暂停计时器,它也必须在第 2 页暂停。

我整天都找不到解决方案……请帮忙。

我的计时器代码:

const Timer = easytimer.Timer;


const getSavedTime = () => JSON.parse(localStorage.getItem('time')) || {};

const instance = new Timer({ startValues: getSavedTime() });
instance.addEventListener('secondsUpdated', () => {
   document.querySelector('.example').textContent = instance.getTimeValues().toString();
   localStorage.setItem('time', JSON.stringify(instance.getTimeValues()));
});

    instance.addEventListener('started', () => localStorage.setItem('running', '1'));
    
    instance.addEventListener('paused', () => localStorage.removeItem('running'));
    
    instance.addEventListener('stopped', () => {
      localStorage.removeItem('time');
      localStorage.removeItem('running');
      document.querySelector('.saved').textContent = '';
      document.querySelector('.example').textContent = '';
    });
    
    document.querySelector('.saved').textContent = localStorage.getItem('time');
    document.querySelector('.example').textContent = instance.getTimeValues().toString();
    
    document.querySelector('.start-button').addEventListener('click', () => instance.start({ startValues: getSavedTime() }));
    document.querySelector('.pause-button').addEventListener('click', () => instance.pause());
    document.querySelector('.stop-button').addEventListener('click', () => instance.stop());
    
    if (localStorage.getItem('running') === '1') {
      instance.start({ startValues: getSavedTime() });
    }

监听事件:

   window.addEventListener('storage', function (e) {

        console.log("storage event occured here");

    },false);

您可以使用BroadcastChannel在同一来源的不同选项卡之间进行通信。

更难的部分是管理哪个选项卡可以“运行”计时器代码以及哪些选项卡只是“监听”事件。 然后,如果正在运行计时器的选项卡关闭,您将如何协调决定哪个其他选项卡应该接管该角色。

更好的选择可能是将计时器代码放在Web Worker (特别是SharedWorker )中,然后使用BroadcastChannel (和/或SharedWorkerport属性)将事件发送到选项卡。

如果幸运的话,您可能无需任何修改就可以让您的easytimer.Timer类在 Web Worker 中运行 - 尽管您仍然需要做一些工作来将其连接到BroadcastChannel

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM