JavaScript; communication between tabs/windows with same origin [duplicate]

I have two windows: window A and window B.

  • window A and window B have same domain
  • window A and window B doesn't have any parent window.
  1. Is it possible for window A to get a reference of window B?
  2. What is the most elegant way to make window A notify something to window B? (including new HTML5 specifications)

Two ways I am aware of doing this:

  • messaging by server: where window B regularly asks the server if window A has notified something
  • messaging by local data (HTML5): when window A wants to notify something it changes the local data, window B regularly checks the local data for any changes.

But the two ways are not so elegant.

For example, it would be nice to get a reference of window B and use window.postMessage() (HTML5)

The ultimate goal is to make something like Facebook where if you open four Facebook tabs and chat in one tab, the chat is up to date in every Facebook tab, which is neat!


Solution 1:

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, performance, 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.

References can be found here:
Webstorage
Webstorage - storage event

Solution 2:

The BroadcastChannel standard allows to do this. Right now it is implemented in Firefox and Chrome (caniuse, mdn):

// tab 1
var ch = new BroadcastChannel('test');
ch.postMessage('some data');

// tab 2
var ch = new BroadcastChannel('test');
ch.addEventListener('message', function (e) {
    console.log('Message:', e.data);
});

Solution 3:

SharedWorker is the WHATWG/ HTML5 spec for a common process that can communicate amongst tabs.