Javascript; communication between tabs/windows with same origin

brillout picture brillout · Feb 10, 2010 · Viewed 69.3k times · Source

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.

Questions:

  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 specs)

Two ways i am aware of doing this:

  • messaging by server: where window B regulary 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 regulary 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)

Ultimate goal is to make something like facebook where if you open 4 facebook tabs and chat in one tab, the chat is up to date in every facebook tab, which is neat!

Answer

brillout picture brillout · Sep 20, 2012

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