Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active May 6, 2025 08:28
Show Gist options
  • Save Kcko/9f09b08369096ffc6c10499159e2087e to your computer and use it in GitHub Desktop.
Save Kcko/9f09b08369096ffc6c10499159e2087e to your computer and use it in GitHub Desktop.
/*
https://javascript.plainenglish.io/3-powerful-ways-to-share-data-across-browser-tabs-in-javascript-a6a98dffa1a3
*/
// 1. local storage
// Sender
localStorage.setItem('sharedData', JSON.stringify({
message: 'Hello from Tab1!',
timestamp: Date.now()
}));
// Receiver
window.addEventListener('storage', (e) => {
if(e.key === 'sharedData') {
const data = JSON.parse(e.newValue);
console.log('Received data:', data);
}
});
// 2. BroadcastChannel API
// Create a channel (use the same channel name across all tabs)
const channel = new BroadcastChannel('app-channel');
// Send a message
channel.postMessage({
type: 'USER_UPDATE',
payload: { name: 'John' }
});
// Receive messages
channel.onmessage = (e) => {
console.log('Received broadcast:', e.data);
};
// Close the connection
window.onunload = () => channel.close();
// 3.SharedWorker Shared Thread
// shared-worker.js
let ports = [];
onconnect = (e) => {
const port = e.ports[0];
ports.push(port);
port.onmessage = (e) => {
// Broadcast to all connected pages
ports.forEach(p => {
if(p !== port) p.postMessage(e.data);
});
};
};
// Page code
const worker = new SharedWorker('shared-worker.js');
worker.port.start();
// Send a message
worker.port.postMessage('Message from Tab A');
// Receive messages
worker.port.onmessage = (e) => {
console.log('Shared thread message:', e.data);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment