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

Igo*_*bin 2 javascript jquery local-storage

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

我知道使用本地存储可能(至少在理论上).能否请您提供代码的小例子?只需在一个标签中发送活动,然后在另一个标签中接收.

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

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

bri*_*ley 6

Localstorage具有您可以订阅以同步其他页面的事件.

注意:如果更新窗口A中的键值,则不会在窗口A中触发该事件.它将在Windows B&C中触发.

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

在几个选项卡中打开此页面.更改输入上的值并将其反映在div中.

这是代码The 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);
});
Run Code Online (Sandbox Code Playgroud)

标记:

<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>
Run Code Online (Sandbox Code Playgroud)

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;
};
Run Code Online (Sandbox Code Playgroud)

来自:http: //www.w3.org/TR/webstorage/#the-storage-event

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