Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RxJs and window's postMessage for intercommunication
import * as Rx from "rxjs/Rx";
import * as uuid from "uuid";
import {IRequest} from "./common";
let button = document.querySelector("button");
let iframe = document.createElement("iframe");
iframe.src = "/proxy.html";
document.body.appendChild(iframe);
button.onclick = function() {
request("https://request.url");
};
function request(url: string) {
const requestId = uuid.v4();
const req: IRequest = {
id: requestId,
payload: {
url
}
};
iframe.contentWindow.postMessage(req, "*");
return Rx.Observable.fromEvent(window, "message")
.filter((messageEvent: MessageEvent) => messageEvent.data && messageEvent.data.id === requestId)
.map((messageEvent: MessageEvent) => messageEvent.data));
}
import * as Rx from "rxjs/Rx";
import {IResponse} from "./common";
const messages = Rx.Observable.fromEvent(window, "message")
.filter((messageEvent: MessageEvent) => messageEvent.data && !!messageEvent.data.id);
messages.subscribe((event: MessageEvent) => {
const response: IResponse = {
id: event.data.id,
payload: event.data.payload
};
event.source.postMessage(response, event.origin);
});
@tuan

This comment has been minimized.

Copy link
Owner Author

@tuan tuan commented Nov 1, 2016

In this sample code, the host page proxy its request to an iframe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment