MessageBridge is a minimal, type-safe utility to enable communication between a parent window and <iframe>
elements or opened windows
using the postMessage
API. It supports both promise-based requests and observable event streams, with optional support for broadcasting from parent to all iframes.
- Promise and observable request/response messaging
- Bidirectional: Parent ↔ Iframe and Parent ↔ window.open
- Auto-handshake on iframe connect
- Supports broadcast messaging (parent to all children)
npm install message-bridge
Or clone locally:
git clone https://github.com/axelmichel/message-bridge.git
cd message-bridge
npm install
import { MessageBridge } from 'message-bridge';
MessageBridge.init();
const iframe = document.getElementById('child-frame') as HTMLIFrameElement;
const result = await MessageBridge.toChild(iframe).sendRequest('getTime');
console.log('Time from iframe:', result);
MessageBridge.toChild(iframe).sendObservable('height').subscribe({
next: (data) => console.log('Height from iframe:', data),
complete: () => console.log('Completed'),
});
const windowInstance = window.open('https://example.com');
MessageBridge.toWindow(windowInstance).listenFor('ping').subscribe(({ request }) => {
// opt. send a response back to the window
MessageBridge.toWindow(windowInstance).respond(request.uid, { pong: true });
// you can also pass the request to another iframe
MessageBridge.toChild(iframe).sendRequest({request});
});
MessageBridge.toChild(iframe).listenFor('ping').subscribe(({ request }) => {
// opt. send a response back to the iframe
MessageBridge.toChild(iframe).respond(request.uid, { pong: true });
});
import {MessageBridge} from "./message-bride";
MessageBridge.connect([iframe1, iframe2]).then(() => {
MessageBridge.broadcastRequest('refreshData', {force: true}).then(console.log);
MessageBridge.broadcastObservable('tickStream').subscribe(({iframeId, value}) => {
console.log(`Tick from ${iframeId}:`, value);
});
});
const result = await MessageBridge.toParent().sendRequest('getConfig');
console.log('Parent config:', result);
MessageBridge.toParent().listenFor(event).subscribe(({ event }) => {
// opt. send a response back to the parent
MessageBridge.toParent().respond(request.uid, { ... });
});
Run all tests:
npm test
Or use the playground:
npm run dev:playground
Then open http://localhost:5173/
in your browser.