javascript / expert
Snippet
Inter-Tab State Sync with BroadcastChannel
In multi-tab applications, keeping state synchronized is a challenge. This pattern uses the BroadcastChannel API inside a Vue Composable to broadcast reactive changes to all other tabs on the same origin, ensuring a consistent user experience.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { ref, watch, onUnmounted } from 'vue';export function useSharedState(key, initialValue) {const state = ref(initialValue);const channel = new BroadcastChannel(`sync_${key}`);channel.onmessage = (event) => {state.value = event.data;};watch(state, (newValue) => {channel.postMessage(JSON.parse(JSON.stringify(newValue)));}, { deep: true });onUnmounted(() => channel.close());return state;}
vue
Breakdown
1
const channel = new BroadcastChannel(`sync_${key}`);
Establish a communication channel specific to the state key.
2
channel.onmessage = (event) => { state.value = event.data; };
Listen for messages from other tabs and update the local reactive state.
3
channel.postMessage(...);
Send the updated state to other tabs whenever the local state changes.
4
onUnmounted(() => channel.close());
Properly close the channel to prevent memory leaks and dangling listeners.