-
-
Save nybatista/67fa1de32352cb4fed8a7964892d8d55 to your computer and use it in GitHub Desktop.
RxJs and window's postMessage for intercommunication
This file contains hidden or 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 hidden or 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