JavaScript
Public
Cross-Tab State Sync with BroadcastChannel
Synchronize lightweight UI state between tabs from the same origin.
#javascript
#broadcastchannel
#browser-api
#state
JavaScript
const channel = new BroadcastChannel('app-preferences');
const preferences = {
theme: 'dark',
compactMode: true,
};
channel.addEventListener('message', (event) => {
if (event.data?.type !== 'preferences-updated') {
return;
}
applyPreferences(event.data.preferences);
});
function updatePreferences(nextPreferences) {
Object.assign(preferences, nextPreferences);
applyPreferences(preferences);
channel.postMessage({
type: 'preferences-updated',
preferences,
});
}
function applyPreferences(nextPreferences) {
document.documentElement.dataset.theme =
nextPreferences.theme;
document.documentElement.classList.toggle(
'compact',
Boolean(nextPreferences.compactMode),
);
}
window.addEventListener('beforeunload', () => {
channel.close();
});