iframe
kkRPC supports bidirectional RPC communication between a page and an iframe through native iframe transports.
export type FrameAPI = { math: { multiply(a: number, b: number): Promise<number> }}
export const frameApi: FrameAPI = { math: { multiply: async (a, b) => a * b }}<script lang="ts"> import { wrap } from "kkrpc" import { iframeParentTransportReady } from "kkrpc/iframe" import type { FrameAPI } from "./api"
let iframeRef: HTMLIFrameElement let api: FrameAPI
async function onIframeLoad() { if (!iframeRef.contentWindow) return const transport = await iframeParentTransportReady(iframeRef.contentWindow) api = wrap<FrameAPI>(transport) }</script>
<iframe bind:this={iframeRef} onload={onIframeLoad} src="/iframe"></iframe><script lang="ts"> import { expose } from "kkrpc" import { iframeChildTransportReady } from "kkrpc/iframe" import { frameApi } from "./api"
const transport = await iframeChildTransportReady() expose(frameApi, transport)</script>Handshake timeout
Section titled “Handshake timeout”The child retries the MessagePort handshake with exponential backoff until the parent accepts a
port. If the parent never responds, it gives up after handshakeTimeoutMs (default 30000) and
iframeChildTransportReady() rejects, instead of retrying forever.
const transport = await iframeChildTransportReady({ handshakeTimeoutMs: 10_000 })