iframe-bridge-kit
v1.1.1
Published
A type-safe communication bridge for iframes. Define strongly typed RPC APIs for cross-window messaging with ease.
Maintainers
Readme
iframe-bridge-kit
iframe-bridge-kit is an iframe communication library based on Vite and Penpal. It uses a Vite plugin to automatically generate type definitions, allowing you to call parent window methods from the iframe (child window) with 100% TypeScript type hints, just like calling local functions.
✨ Features
- 🔒 Type Safe: Automatically generates
.d.tsbased on source code; parent and child windows share identical types. - 🚀 Zero Runtime Definition: No need to manually define interfaces in the child window; simply import the generated bridge file to use.
- 📡 RPC Style: Call cross-window methods just like calling
asyncfunctions. - ⚡ Event Mechanism: Supports sending strongly-typed broadcast messages from the parent window to the child window.
- 🛠 Vite Integration: Designed specifically for the Vite ecosystem with HMR support.
📦 Installation
You need to install both iframe-bridge-kit and its peer dependency penpal.
npm install iframe-bridge-kit penpal
# or
pnpm add iframe-bridge-kit penpal
# or
yarn add iframe-bridge-kit penpal⚙️ Configuration
Import the plugin in your vite.config.ts.
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue' // or other framework plugins
import vitePluginIframeBridge from 'iframe-bridge-kit/vite'
export default defineConfig({
plugins: [
vue(),
vitePluginIframeBridge({
// Output directory, default is 'src/bridges' (recommended to place under src for easy import)
outDir: 'src/bridges',
// Whether to generate full code (including Penpal dependency), default is true
full: true
})
]
})📖 Usage Guide
1. Parent Window (Host/Parent)
In the parent window, use defineBridge to define the methods and event types exposed to the iframe.
// src/views/Parent.vue (or other .ts files)
import { defineBridge } from 'iframe-bridge-kit'
import { ref, onMounted } from 'vue'
// Define event types sent from Parent to Child
interface EmitMap {
'theme-change': { mode: 'dark' | 'light' }
'user-logout': void
}
// 1. Define Bridge
// The first argument 'app-bridge' is the bridge name, used for folder generation
export const mainBridge = defineBridge<EmitMap>('app-bridge', {
// Methods exposed to the iframe
async getUserInfo(id: string) {
return { id, name: 'John Doe', role: 'admin' }
},
updateTitle(title: string) {
document.title = title
return true
}
})
// 2. Bind iframe
const iframeRef = ref<HTMLIFrameElement>()
onMounted(async () => {
if (iframeRef.value) {
const child = await mainBridge.create(iframeRef.value)
// Send message to iframe
child.emit('theme-change', { mode: 'dark' })
}
})Note: After saving the file, the Vite plugin will automatically scan for
defineBridgeand generate the corresponding type definitions and runtime code undersrc/bridges/app-bridge/.
2. Child Window (Iframe/Child)
In the iframe project, directly import the file generated by the plugin. All API methods have strict type inference.
// src/views/IframeChild.vue
// Import from the generated directory (path depends on your outDir config)
import createParentBridge from '../bridges/app-bridge'
const parent = createParentBridge()
// Wait for connection initialization (optional)
parent.onInit(() => {
console.log('Bridge connected!')
})
// 1. Call parent window methods (RPC)
async function fetchUser() {
// ✅ Full type hints for id and return value here!
const user = await parent.getUserInfo('123')
console.log(user.name)
}
// 2. Listen for parent window messages
// ✅ Type hints for 'theme-change' and callback data
parent.onMessage('theme-change', (data) => {
console.log('New theme:', data.mode)
})3. Reverse Calls: Child Defines API, Parent Calls It
If the API is defined inside the iframe, the parent can import the same generated file and explicitly pass the target Window to establish the connection. Each default factory call returns an independent instance, so it works cleanly with multiple iframes.
// inside iframe
import { defineBridge } from 'iframe-bridge-kit'
export const childBridge = defineBridge('child-api', {
async getSelection() {
return window.getSelection()?.toString() || ''
}
})
childBridge.create(window.parent)// parent window
import { createBridgeClient } from '../bridges/child-api'
const iframeEl = document.querySelector('iframe')!
if (!iframeEl.contentWindow) {
throw new Error('iframe is not ready')
}
const child = createBridgeClient(iframeEl.contentWindow)
const text = await child.getSelection()The default child-window flow can call the default function, which reuses a singleton client connected to window.parent. When the parent wants to call APIs defined by the iframe, create an independent instance with createBridgeClient(iframe.contentWindow).
🧩 Type Support Details
The core magic of iframe-bridge-kit lies in how it handles types.
When you define methods:
getUserInfo(id: string): Promise<User>The plugin extracts the User interface (even types imported from node_modules) and copies it into the generated index.d.ts. This means the child window does not need access to the parent's source code or dependencies to get perfect type hints.
Supported Type Features
- Basic types (string, number, boolean)
- Interfaces & Type Aliases
- Generic Expansion
- Third-party library types (automatically handles import paths)
🔌 API Reference
defineBridge<TEmit>(name, methods)
- name:
string- Bridge name, determines the generated directory name. - methods:
Object- Collection of methods exposed to the child window. - TEmit:
Generic- (Optional) Defines the event type mapping for messages sent viaemitfrom the parent.
Returns an object containing:
create(target, allowedOrigins?): Initializes the connection.targetmay be anHTMLIFrameElementorWindow, and the return value is an{ emit, destroy }object.
Vite Plugin Options (IframeBridgeOptions)
| Option | Type | Default | Description |
|:---|:---|:---|:---|
| outDir | string | 'bridges' | Output directory for generated code. Recommended 'src/bridges'. |
| allowedOrigins | string[] | ['*'] | List of allowed origin domains for communication. |
| full | boolean | true | Whether to generate code containing full dependencies. |
| preserveModules | string[] | [] | Preserve imports for specific modules instead of expanding types (e.g., ['vue']). |
Generated Runtime API
Assuming outDir is src/bridges and the bridge name is my-bridge, you can import from src/bridges/my-bridge:
default(createBridge): Returns the default singletonBridgeClientconnected towindow.parent, suitable for child-to-parent calls.createBridgeClient(remoteWindow, allowedOrigins?): Named multi-instance factory export. It requires an explicitWindowand is suitable when the parent manages one or more iframes.client.onMessage(type, callback, once?): Listen for events sent by the remote bridge.client.offMessage(type, callback?): Remove an event listener.client.onInit(callback): Triggered when that instance is successfully connected.client.isInit(): Returns that instance's connection status.client.destroy(): Destroy the connection maintained by that instance.
⚠️ Notes
- Same-Origin Policy: While Penpal simplifies postMessage, please ensure
allowedOriginsis correctly configured for security. - Build Order: During production builds, ensure files containing
defineBridgeare correctly processed. Usually, as long as these files are within your source tree (referenced via import), the Vite plugin will scan them. - Serialization: Function values passed directly or nested in arrays/plain objects are proxied automatically, so callback-style APIs can cross the bridge. DOM nodes and other non-transferable objects are still not supported.
License
MIT
