JavaScript的;相同来源的标签/窗口之间的通信 [英] Javascript; communication between tabs/windows with same origin

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

问题描述

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




  • 窗口A和窗口B具有相同的域

  • 窗口A和窗口B没有任何父窗口。



问题:


  1. 窗口A有可能获得窗口B的引用吗? b
    (包括新的HTML5规范)


  2. 什么是最优雅的方式让窗口A通知窗口B? ol>

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


    • 通过服务器发送消息:其中窗口B定期询问服务器,如果窗口A已通过本地数据(HTML5)通知了某些消息:当窗口A想要通知某事它改变了本地数据时,窗口B定期检查本地数据对于任何改变。


    但这两种方式并不那么优雅。例如,获得窗口B并使用window.postMessage()(HTML5)



    最终目标是制作类似于Facebook的内容,如果您打开4个Facebook标签并在一个标签中聊天,在每个Facebook标签中都是最新的,这是很整洁的!

    解决方案

    我坚持共享本地数据解决方案该问题使用 localStorage 。它似乎是可靠性,性能和浏览器兼容性方面的最佳解决方案。

    localStorage 所有现代浏览器。


    $ b $ <存储事件触发其他标签更改为 localStorage的。这对于沟通是非常方便的。



    引用可以在这里找到:

    Webstorage

    Webstorage - 存储事件


    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!

    解决方案

    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 is implemented in all modern browsers.

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

    References can be found here:
    Webstorage
    Webstorage - storage event

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

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