'window.postmessage() to communicate between applications in different tabs

Is there a chance to use window.postmessage() to communicate between two different applications in different tabs in the same browser?

I know you can do it between application and iFrame, but how about different tabs?

Update:

Case scenario:

  1. user plays audio from vk.com in one tab

  2. user starts playing video from youtube.com in another tab

  3. youtube.com sends postmessage() to vk.com that video started playing

  4. vk.com makes audio silent

Thanks



Solution 1:[1]

It can be done if you use an "intermediate page" loaded in an iFrame.

The (theoretical) solution uses two separate methods of inter-page communication:

  • window.postMessage()
  • localStorage or sessionStorage - see this guide for how this works; the technique involves setting values in one iFrame, and listening for events in the other iFrame.

The "intermediate page" acts as a proxy, translating message events into localStorage events, and vice-versa. If you load this "intermediate page" in an iFrame from both pages, then any messages you post in one tab will pop out in the other tab:

[Tab 1] --(postMessage)--> [iFrame 1]
                                |
                          (localStorage)
                                |
                                v
                           [iFrame 2] --(postMessage)--> [Tab 2]

If one of the tabs is on the same domain as the intermediate page (illustrated here as Tab 2), this can be simplified (without affecting the other tab's setup).

[Tab 1] --(postMessage)--> [iFrame 1]
                                |
                          (localStorage)
                                |
                                v
                             [Tab 2]

Solution 2:[2]

following up this thread. Same situation here. Opening a different origin using window.open("originB") from origin A. As Lakhan Jain said, theoretically we can use window.postMessage() (https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage) for communicating between windows with different origins. we would just need to have the reference of the other window.

The problem is that we are not able to listen the events that come from the origin A even if we delay the postMessage until origin B is fully loaded.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wyck
Solution 2 Victor Mendigorri