@roughapp/plugin
v0.1.2
Published
SDK bridge for parent ↔ iframe communication using `postMessage` + `MessageChannel`.
Readme
@roughapp/plugin
SDK bridge for parent ↔ iframe communication using postMessage + MessageChannel.
This package defines the plugin SDK contract. Right now the SDK includes one method:
reportSize({ width, height }): called by the iframe to inform the parent of its rendered size.
Install
pnpm add @roughapp/plugin
# or
npm i @roughapp/pluginSDK API
type IframeSize = { width: number; height: number };
interface PluginSdkApi {
reportSize(size: IframeSize): void | Promise<void>;
}Parent app usage
The parent implements PluginSdkApi and registers each iframe.
import { ParentRpcHost, type PluginSdkApi } from '@roughapp/plugin';
const host = new ParentRpcHost({
targetOrigin: window.location.origin,
channel: 'my-plugin'
});
const iframe = document.querySelector('iframe#plugin')!;
host.registerFrame('plugin-1', {
frameWindow: iframe.contentWindow!,
createApi: (): PluginSdkApi => ({
reportSize({ width, height }) {
iframe.style.width = `${width}px`;
iframe.style.height = `${height}px`;
}
})
});
host.start();Iframe app usage
The iframe can only call methods from PluginSdkApi.
import { IframeRpcClient } from '@roughapp/plugin';
const client = new IframeRpcClient('plugin-1', {
targetOrigin: window.location.origin,
channel: 'my-plugin'
});
const sdk = await client.connect();
await sdk.reportSize({
width: document.documentElement.scrollWidth,
height: document.documentElement.scrollHeight
});Important rules
frameIdmust match on both sides.channelmust match on both sides.targetOriginmust match expected origin.- Parent must call
host.start()before iframe connects.
Svelte lifecycle tip
- Parent: create/start in
onMount, stop inonDestroy. - Iframe: connect in
onMount, disconnect inonDestroy.
