@zhyi64/onepc-bridge
v0.1.1
Published
Unified cross-iframe communication SDK for nested iframe architecture (onepcweb → intelligent-web → openclaw)
Maintainers
Readme
@zhyi64/onepc-bridge
统一的跨 iframe 通信 SDK,用于多层嵌套 iframe 架构的消息路由与转发。
架构
A (onepcweb) ← 根节点
↑ postMessage
B (intelligent-web) ← 中间层,自动路由
↑ postMessage
C (openclaw) ← 叶节点安装
npm install @zhyi64/onepc-bridge快速开始
叶节点 (C - openclaw)
import { OnePcBridge } from '@zhyi64/onepc-bridge'
const bridge = new OnePcBridge({
nodeId: 'openclaw',
allowedOrigins: ['https://...'],
parentWindow: window.parent,
debug: true,
})
bridge.init()
// 直接发送给 A,无需知道中间经过 B
bridge.send('onepcweb', 'menu', { currentMenu: 'settings' })
// 监听来自 A 的消息
bridge.on('theme', (payload) => {
document.documentElement.setAttribute('data-theme', payload.theme)
})中间节点 (B - intelligent-web)
import { OnePcBridge } from '@zhyi64/onepc-bridge'
const bridge = new OnePcBridge({
nodeId: 'intelligent',
allowedOrigins: [CHILD_ORIGIN, A_ORIGIN],
parentWindow: window.parent,
getChildWindow: () => iframeRef.value?.contentWindow ?? null,
})
// 注册自动路由 — 一行搞定,无需手动 if/switch 转发
bridge.addRoute('openclaw', 'onepcweb') // C→A
bridge.addRoute('onepcweb', 'openclaw') // A→C
bridge.init()根节点 (A - onepcweb)
import { OnePcBridge } from '@zhyi64/onepc-bridge'
const bridge = new OnePcBridge({
nodeId: 'onepcweb',
allowedOrigins: ['https://...'],
getChildWindow: () => document.querySelector('#iframe')?.contentWindow,
})
bridge.init()
// 直接发送给 C,自动经过 B 中转
bridge.send('openclaw', 'theme', { theme: 'dark' })
// 监听来自 C 的消息
bridge.on('menu', (payload, envelope) => {
console.log('来自 C 的菜单消息:', payload)
})API
new OnePcBridge(config)
| 参数 | 类型 | 说明 |
|------|------|------|
| nodeId | NodeId | 当前节点标识 |
| allowedOrigins | string[] | Origin 白名单 |
| parentWindow? | Window | 父窗口引用 |
| getChildWindow? | () => Window \| null | 获取子窗口引用的函数 |
| debug? | boolean | 开启调试日志 |
方法
| 方法 | 说明 |
|------|------|
| init() | 注册全局 message 监听 |
| destroy() | 移除监听,清理资源 |
| send(target, type, payload?) | 发送消息(自动路由) |
| on(type, handler) | 注册消息处理器,返回 unsubscribe 函数 |
| addRoute(from, to) | 注册自动路由(中间层使用) |
| removeRoute(from, to) | 移除路由 |
特性
- 自动路由 — 中间层只需
addRoute(),无需手动转发 - 旧格式兼容 — 自动识别新旧消息格式,新旧代码可并行
- Origin 安全 — 集中管理白名单
- 无框架依赖 — 纯 JS,Vue/React/原生均可使用
- TypeScript 支持 — 内置类型声明
License
MIT
