/ Gists / Share data among browser tabs
On gists

Share data among browser tabs

JavaScript

share.js Raw #

/*
  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);
};