Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 990
brillout Avatar asked Feb 10 '10 12:02

brillout


People also ask

Is localStorage shared between tabs?

The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

What is window postMessage?

postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.


1 Answers

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

like image 91
brillout Avatar answered Sep 24 '22 09:09

brillout