Is it possible to have event-based communication b

2019-02-19 14:53发布

问题:

This question already has an answer here:

  • Communication between tabs or windows 9 answers

Is it possible to have event-based communication between browser tabs/windows?

I known that it could be (at least theoretically) possible using local storage. Could you please provide small example of code doing that? Just send event in one tab, and receive it in another.

Are there any libraries/jquery-plugins that do that?

(I know that I can communicate between windows/tabs of the same browser using cookies; but that is not what I need; I would prefer event-based approach, I don't want recheck the state of the cookies every millisecond).

回答1:

Localstorage has events that you can subscribe to to syncronize other pages.

Note: If you update a key's value in window A, the event will not be triggered in window A. It will be triggered in windows B & C.

Here is a demo: http://html5demos.com/storage-events

Open this page in several tabs. change the value on the input and see it reflected in divs.

Here is the code 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);
});

Markup:

<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>

The HTML 5 spec discusses all the information passed in the event:

[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;
};

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

Using this event, you can make other pages react to when a specific key in local storage is updated.



回答2:

Give SignalRamp a chance.

You can attach any of the bindable class names to elements to syncronize the corresponding mousedown, mouseup, hover (mouseover, mouseout) or click events in the UI.