Created
November 1, 2016 17:40
-
-
Save tuan/8a1ca1b0376a5056f4141972b171c89e to your computer and use it in GitHub Desktop.
RxJs and window's postMessage for intercommunication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In this sample code, the host page proxy its request to an iframe.