iframe-bridge-kit
v1.0.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 ParentApi, { onMessage, onInit } from '../bridges/app-bridge'
// Wait for connection initialization (optional)
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 ParentApi.getUserInfo('123')
console.log(user.name)
}
// 2. Listen for parent window messages
// ✅ Type hints for 'theme-change' and callback data
onMessage('theme-change', (data) => {
console.log('New theme:', data.mode)
})🧩 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(iframeEl, allowedOrigins?): Initializes the connection and returns an{ emit }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 Child API
Assuming outDir is src/bridges and the bridge name is my-bridge, you can import from src/bridges/my-bridge:
default(ParentApi): A proxy object containing all parent methods. All methods return aPromise.onMessage(type, callback, once?): Listen for events sent by the parent.offMessage(type, callback?): Remove an event listener.onInit(callback): Triggered when the connection is successfully established.isInit(): Returns the current connection status.
⚠️ 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. - JSON Serialization: Data transmitted across windows must be JSON serializable (Functions, DOM nodes, etc., are not supported).
License
MIT
