Skip to content

Instantly share code, notes, and snippets.

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";
button.onclick = function() {
function request(url: string) {
const requestId = uuid.v4();
const req: IRequest = {
id: requestId,
payload: {
iframe.contentWindow.postMessage(req, "*");
return Rx.Observable.fromEvent(window, "message")
.filter((messageEvent: MessageEvent) => && === requestId)
.map((messageEvent: MessageEvent) =>;
import * as Rx from "rxjs/Rx";
import {IResponse} from "./common";
const messages = Rx.Observable.fromEvent(window, "message")
.filter((messageEvent: MessageEvent) => && !!;
messages.subscribe((event: MessageEvent) => {
const response: IResponse = {
event.source.postMessage(response, event.origin);

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