Skip to content

Instantly share code, notes, and snippets.

@tuan
Created November 1, 2016 17:40
Show Gist options
  • Save tuan/8a1ca1b0376a5056f4141972b171c89e to your computer and use it in GitHub Desktop.
Save tuan/8a1ca1b0376a5056f4141972b171c89e to your computer and use it in GitHub Desktop.
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
Copy link
Author

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