window.postmessage()在不同选项卡中的应用程序之间进行通信 [英] window.postmessage() to communicate between applications in different tabs

查看:170
本文介绍了window.postmessage()在不同选项卡中的应用程序之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能使用window.postmessage()在同一浏览器中的不同标签中的两个不同的应用程序之间进行通信吗?



我知道你可以在应用程序和iFrame,但如何不同的标签?



更新:



案例:


  1. 用户从一个标签中播放vk.com的音频


  2. <

    youtube.com会向vk.com发送
    视频开始播放的postmessage()消息

    >
  3. vk.com使音频无声


$ b

感谢



这个(理论的)解决方案是可以做到的,如果你使用一个iFrame中加载的中间页面使用两种单独的页面间通信方法:




  • window.postMessage()

  • localStorage (请参阅本指南,了解如何运作)



中间页充当代理,将消息事件转换为localStorage事件,反之亦然。如果您在两个网页的iFrame中加载此中间页,则您在一个标签中发布的任何邮件都会在其他标签中弹出:

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

如果其中一个标签与中间页位于同一个网域 Tab 2 ),这可以简化(不影响其他标签的设置)。

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


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

解决方案

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 (see this guide for how this works)

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]

这篇关于window.postmessage()在不同选项卡中的应用程序之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆