2

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

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

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

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

4

2 回答 2

6

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

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

于 2013-02-09T22:09:36.550 回答
0

SignalRamp一个机会。

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

于 2013-02-06T21:20:09.683 回答