Javascript; communication between tabs/windows wit

2019-01-01 03:44发布

This question already has an answer here:

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!

7条回答
若你有天会懂
2楼-- · 2019-01-01 04:19

Besides the upcoming SharedWorker, you can also use cross-document messaging, which is much more widely supported. In this scenario, there must a be a main window that is responsible for opening all other windows with window.open. The child windows can then use postMessage on their window.opener.

If using flash is an option for you, there is also the much older LocalConnection virtually supported on any client with flash installed (example code).

Other fallbacks methods:
postMessage plugin for jQuery with window.location.href fallback for older browsers
cookie-based solution for non-instant communication

查看更多
登录 后发表回答