Call functions in an iframe using promises and window.postMessage()
.
npm i simple-iframe-rpc
In the iframe window
import Listener from "simple-iframe-rpc/listener";
const listener = new Listener({
add: (a, b) => a + b,
sub: (a, b) => a - b,
});
listener.listen(window, "*");
In the parent window
import {connect} from "simple-iframe-rpc/sender";
const iframe = document.getElementById("my-iframe");
const rpc = connect(window, iframe.contentWindow, "*");
const value = await rpc.add(2, 3);
It's recommended to specify the targetOrigin
instead of using "*"
.
import {connect} from "simple-iframe-rpc/sender";
type MathRPC = {
add: (a: number, b: number) => Promise<number>;
sub: (a: number, b: number) => Promise<number>;
}
const iframe = document.getElementById("my-iframe");
const rpc = connect<MathRPC>(window, iframe.contentWindow, "*");
You can configure RPC to give a timeout if there's no response from the iframe window
const rpc = connect(window, iframe.contentWindow, "*", {timeout: 3000});
Deleting the magic handler
property will remove the event listener.
delete rpc.handler;
In Typescript, use delete (rpc as any).handler
.
The library can also be used with Web workers
const myWorker = new Worker('worker.js');
const rpc = connect(window, myWorker, "*");
in worker.js
// ...
listener.listen(self, "*");