javascript / expert
Snippet
Cross-Tab State Synchronization with BroadcastChannel
The BroadcastChannel API allows communication between different browsing contexts (tabs, windows) of the same origin. Integrating it with Svelte runes ensures that all open tabs react instantly to state changes initiated in one.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>let status = $state('offline');const channel = new BroadcastChannel('app_sync');channel.onmessage = (event) => {status = event.data;};function updateStatus(newStatus) {status = newStatus;channel.postMessage(newStatus);}</script><p>Status: {status}</p><button onclick={() => updateStatus('online')}>Go Online</button>
svelte
Breakdown
1
const channel = new BroadcastChannel('app_sync');
Creates a communication pipe named 'app_sync' shared across tabs.
2
channel.onmessage = (event) => { status = event.data; };
Updates the local reactive state when a message is received from another tab.
3
channel.postMessage(newStatus);
Broadcasts the new state to all other instances of the application.