【问题标题】:Is it possible to have event-based communication between browser windows? [duplicate]浏览器窗口之间是否可以进行基于事件的通信? [复制]
【发布时间】:2013-01-22 01:01:48
【问题描述】:

是否可以在浏览器选项卡/窗口之间进行基于事件的通信?

我知道(至少在理论上)使用 本地存储 是可能的。您能否提供这样做的代码的小示例?只需在一个选项卡中发送事件,然后在另一个选项卡中接收。

是否有任何库/jquery 插件可以做到这一点?

(我知道我可以使用 cookie 在同一浏览器的窗口/选项卡之间进行通信;但这不是我需要的;我更喜欢基于事件的方法,我不想每毫秒重新检查 cookie 的状态)。

【问题讨论】:

标签: javascript jquery local-storage


【解决方案1】:

SignalRamp一个机会。

您可以将任何可绑定的类名称附加到元素,以在 UI 中同步相应的 mousedown、mouseup、hover(mouseover、mouseout)或单击事件。

【讨论】:

    【解决方案2】:

    Localstorage 包含您可以订阅以同步其他页面的事件。

    注意:如果您在窗口 A 中更新某个键的值,则该事件不会在窗口 A 中触发。它将在窗口 B 和 C 中触发。

    这是一个演示: http://html5demos.com/storage-events

    在多个选项卡中打开此页面。更改输入的值并查看它在 div 中的反映。

    这里是 Javascript 代码:

    var dataInput = document.getElementById('data'),
    output = document.getElementById('fromEvent');
    
    // handle updates to the storage-event-test  key in other windows
    addEvent(window, 'storage', function (event) {
      if (event.key == 'storage-event-test') {
        output.innerHTML = event.newValue;
      }
    });
    
    // Update the storage-event-test key when the value on the input is changed
    addEvent(dataInput, 'keyup', function () {
      localStorage.setItem('storage-event-test', this.value);
    });
    

    标记:

    <div>
          <p>Your test data: <input type="text" name="data" value="" placeholder="change me" id="data" /> <small>(this is only echoed on <em>other</em> windows)</small></p>
          <p id="fromEvent">Waiting for data via <code>storage</code> event...</p>
    </div>
    

    HTML 5 规范讨论了事件中传递的所有信息:

    [Constructor(DOMString type, optional StorageEventInit eventInitDict)]
    interface StorageEvent : Event {
      readonly attribute DOMString key;
      readonly attribute DOMString? oldValue;
      readonly attribute DOMString? newValue;
      readonly attribute DOMString url;
      readonly attribute Storage? storageArea;
    };
    
    dictionary StorageEventInit : EventInit {
      DOMString key;
      DOMString? oldValue;
      DOMString? newValue;
      DOMString url;
      Storage? storageArea;
    };
    

    发件人:http://www.w3.org/TR/webstorage/#the-storage-event

    使用此事件,您可以让其他页面在本地存储中的特定键更新时做出反应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-09
      • 2011-05-04
      • 2011-07-24
      • 2013-10-21
      相关资源
      最近更新 更多