WebAPI/WebSocketOverApps

From MozillaWiki
Jump to navigation Jump to search

WebSocketOverApp API provides WebSocket connections between any pair of Apps on a device. An WebApp can create WebSocket connections to other Apps on the device, so they can pass messages through the connection.

API

interface WebSocket : EventTarget {
  ...
  // The URL of the peer App.
  readonly attribute DOMString peerUrl;

  // The protocols supported by the client.
  readonly attribute DOMString[] clientProtocols;

  // The server side call this function to start a given protocol; one of clientProtocols.
  void accept(DOMString protocol);
  ...
};

clientProtocols and accept() are added to provide server side features. clientProtocols is what client side passed as the 2nd argument of WebSocket constructor. The server side can check this list to find out any one of protocols that is supported by itself. If not, just skip the request. If there is any supported protocol, call accept() to start the protocol.

The protocols, here, can be used as the intents or services provided by the server Apps.

Client Side

var ws = new WebSocket("wsapp://appid/", ["intentAsProtocol"]);
ws.onopen = function () {...};
ws.onerror = function () {...};
ws.onclose = function () {...};

Server Side

navigator.mozSetMessageHandler("wsconnect", function (request) {
  var ws = request.value;
  if (ws.clientProtocols.indexOf("intentAsProtocol") == -1) {
    return;
  }
  ws.accept("intentAsProtocol");
});

Manifest

{
  "name": "my application",
  ...
  "wsapp": {
    servers: ["server app1", "server app2", ...]  // allowed to connect to two Apps
  }
}

Work with DeviceIndexedDB

Use Case