JavaScript: sharing data between tabs

Viewed 73962

What is the best way to share data between open tabs in a browser?

12 Answers

For a more modern solution check out https://stackoverflow.com/a/12514384/270274

Quote:

I'm sticking to the shared local data solution mentioned in the question using localStorage. It seems to be the best solution in terms of reliability, efficiency, and browser compatibility.

localStorage is implemented in all modern browsers.

The storage event fires when other tabs makes changes to localStorage. This is quite handy for communication purposes.

Reference:
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/#the-storage-event

The BroadcastChannel standard allows doing this. see MDN BroadcastChannel

// Connection to a broadcast channel
const bc = new BroadcastChannel('test_channel');

// Example of sending of a very simple message
bc.postMessage('This is a test message.');

// A handler that only logs the event to the console:
bc.onmessage = function (ev) { console.log(ev); }

// Disconnect the channel
bc.close();

enter image description here

This can be done using BroadcastChannel API in javascript. Let's say you have opened two different pages in a different tab and want to update the first page when the user changes some values in the second page you can do that like below.

First page

const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.onmessage = function(e) {
     console.log('ticket updated')
 };

Second page

const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.postMessage();

Now when you can postMessage it will trigger the onmessage on the first page.

Also, you can pass data like the below.

const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.postMessage({message:'Updated'});


const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.onmessage = function(e) {
     console.log('ticket updated',e.data)
 };
Related