Package Exports
- @widget-kit/rpc
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@widget-kit/rpc) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
@widget-kit/rpc
Establishes connection between two windows allowing both to send and handle requests.
Install
$ npm install --save @widget-kit/rpcUsage
// Main window:
const hostConnection = createConnection(
iframe.contentWindow,
'https://remote.example.com'
);
hostConnection.handle('ping', (respond) => {
respond('pong');
});
// Iframe (loaded from https://remote.example.com):
const widgetConnection = createConnection(window.parent);
const pingRequest = createRequest('ping');
widgetConnection.send(pingRequest, (response) => {
console.log(response.payload); // prints 'pong'
});API Reference
createConnection(targetWindow, [targetOrigin])
Returns Connection object with send and handle methods.
targetWindow: a reference to remote window.targetOrigin: allows to restrict windows communication by origin. IftargetWindoworigin does not match no request would be sent nor accepted from it.
send(request, [onResponse])
Sends prepared request.
request: a plain object containing request method, arguments list and set of service fields. UsecreateRequesthelper to create proper request object.onResponse: response handler. AcceptsResponseobject withpayloadand optionalerrorfields.
handle(method, handler)
Registers request handler for a given method.
method: an unique method identifier. It's recommended to have prefix with your app name for custom methods (likemyAwesomeApp.analytics.sendEvent).handler: a handler function that accepts response callback and method arguments. You can call response callback at any time passing to it result or error.
Example:
connection.handle('myapp.divide', (respond, a, b) => {
if (b === 0) {
respond(null, 'Whoops, you\'re trying to divide by zero!');
} else {
respond(a / b);
}
});createRequest(method, ...args)
Creates request object that could be sent later.
method: a name of the called method.args: arguments that would be passed to method handler.
Example:
// We can make own "request creator" helper
const sum = (a, b) => createRequest('myapp.sum', a, b);
// And then send this request with different arguments easily
connection.send(sum(1, 1));
connection.send(sum(5, 5));