CodShot
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();
});

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support