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

前端 未结 1 1942
失恋的感觉
失恋的感觉 2021-01-03 17:08

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 a

相关标签:
1条回答
  • 2021-01-03 17:40

    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]
    
    0 讨论(0)
提交回复
热议问题