Angular: how to call a function at the same time in 2 different tabs

Viewed 140

I need to perform a particular test in the web app I am creating. For this I have to open 2 different tabs in my browser and run the application in the 2 tabs.

Then I want to run the same function at the same time (console.log("toto") in the example) in the 2 tabs in order to observe the result in console.

For this I created a variable that contains the current date and a variable that contains the due date, then I subtract between these two variables. When the result is equal to 0, then function triggers in the 2 tabs. The goal is to launch the same function in the 2 open tabs, for example at 17:00

I tried to do this with the following code which is bad:

let currentTime = Date.now();
let timeToLaunch = Date.parse("Wed, 04 August 2021 17:00");
let go = currentTime - timeToLaunch;

let goObservable = of(go);
goObservable.subscribe((value) => {
  console.log(value);
  if (value === 0) console.log("toto");
});

I was thinking about using setTimeout(), but the problem is that I'll have a method run lag between the time I launch the application in tab 1 and tab 2. So don’t know how to do it (how to laucnh the function at the same time in the 2 tabs)

Thanks for your help

1 Answers

Using setInterval and periodically check due date is the easiest option. If you set the checking interval too low and don't bother with performance it might be an option.

But yes, there will be some lag.

Other option is to use - Broadcast Channel. This will enable you intertab communication if it is the same origin (which I suppose is).

You can implement it in a following way:

var channel = new BroadcastChannel('my_channel');

channel.postMessage('Test message.'); // send
channel.onmessage = function (ev) { console.log(ev); } // receive

By using this you can have 'master' tab which checks whether due date is met. And when so it broadcasts message to other tabs to launch their function.

Related