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:
-
LocalStorage +
storageevent- 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 theplayerActionkey, stop the player.
- When clicking the "stop" button in one tab, we write a special value to localStorage, for example,
-
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.onmessageand respond to the command.
- Create a channel:
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.