I was searching for a way how to communicate between multiple tabs or windows in a browser (on the same domain, not CORS).
I am using timer and it should working on all site pages. If there's a way to stop/pause/play timer on all pages (new windows) simultaneously ?
For example I have 2 tabs - page 1 and page 2... on both pages I have running the same timer. If I click pause timer on page 1 it must pause on page 2 too.
I can't find a solution all day long ... help please.
My timer code:
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() });
}
listen event:
window.addEventListener('storage', function (e) {
console.log("storage event occured here");
},false);
You can use BroadcastChannel to communicate between different tabs within the same origin.
The harder part would be managing which tab gets to "run" the timer code and which tabs just "listen" to the events. Then, if the tab that was running the timer got closed, how would you coordinate deciding which other tab should take over that role.
A better option might be to put the timer code in a Web Worker (specifically a SharedWorker), and then just use BroadcastChannel (and/or maybe the port property of the SharedWorker) to send the events out to the tabs.
If you're lucky, you might be able to get your easytimer.Timer class to run within a Web Worker without any modifications - although you would still need to do some work to hook it up to the BroadcastChannel.