Sobes.tech
Middle

There is a player on the page. How would you implement communication between tabs so that when the stop button is pressed on one tab, playback stops on the other tab?

sobes.tech AI

Answer from AI

There are several approaches to facilitate communication between browser tabs:

  1. LocalStorage + storage event

    • When clicking the "stop" button in one tab, we write a special value to localStorage, for example, localStorage.setItem('playerAction', 'stop').
    • In other tabs, listen for the window.addEventListener('storage', ...) event, and upon detecting a change in the playerAction key, stop the player.
  2. Broadcast Channel API

    • Create a channel: const bc = new BroadcastChannel('player_channel').
    • When clicking "stop", send a message: bc.postMessage('stop').
    • In other tabs, listen for bc.onmessage and respond to the command.

The Broadcast Channel API is a more modern and convenient method, but it is not supported in all browsers (though most modern browsers do support it).

Example with LocalStorage:

// In each tab
window.addEventListener('storage', (event) => {
  if (event.key === 'playerAction' && event.newValue === 'stop') {
    // Stop the player
    player.stop();
  }
});

// When clicking stop
function onStopClick() {
  player.stop();
  localStorage.setItem('playerAction', 'stop');
}

Thus, changes in localStorage serve as a signal for other tabs.

There is a player on the page. How would you… - sobes.tech