JavaScript;具有相同来源的选项卡/窗口之间的通信 [英] JavaScript; communication between tabs/windows with same origin

查看:29
本文介绍了JavaScript;具有相同来源的选项卡/窗口之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个窗口:窗口 A 和窗口 B.

I have two windows: window A and window B.

  • 窗口 A 和窗口 B 具有相同的域
  • 窗口 A 和窗口 B 没有任何父窗口.
  1. 窗口 A 是否有可能获得窗口 B 的引用?
  2. 让窗口 A 通知窗口 B 的最优雅的方式是什么?(包括新的 HTML5 规范)

我知道这样做的两种方式:

Two ways I am aware of doing this:

  • 服务器发送消息:窗口 B 定期询问服务器窗口 A 是否通知了某些内容
  • 通过本地数据发送消息 (HTML5):当窗口 A 想要通知某事它更改了本地数据时,窗口 B 会定期检查本地数据是否有任何更改.

但这两种方式都不是那么优雅.

But the two ways are not so elegant.

例如,获得窗口 B 的引用并使用 window.postMessage() (HTML5) 会很好

For example, it would be nice to get a reference of window B and use window.postMessage() (HTML5)

最终目标是制作类似于 Facebook 的东西,如果您打开四个 Facebook 标签并在一个标签中聊天,则每个 Facebook 标签中的聊天都是最新的,这很简洁!

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!

推荐答案

我坚持使用 localStorage 问题中提到的共享本地数据解决方案.就可靠性、性能和浏览器兼容性而言,它似乎是最好的解决方案.

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 已在所有现代浏览器中实现.

localStorage is implemented in all modern browsers.

storage 事件在 other 选项卡对 localStorage 进行更改时触发.这对于交流来说非常方便.

The storage event fires when other tabs makes changes to localStorage. This is quite handy for communication purposes.

参考资料可以在这里找到:
网络存储
Webstorage - 存储事件

References can be found here:
Webstorage
Webstorage - storage event

这篇关于JavaScript;具有相同来源的选项卡/窗口之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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