fast-bridge
v0.0.3-alpha
Published
Fast and secure iframe communication bridge
Maintainers
Readme
🚀 Fast Bridge
一个轻量级、高性能的 iframe 通信库,基于 MessageChannel API 实现,提供安全、可靠的跨页面通信解决方案。
✨ 特性
- 🔒 安全可靠:基于 MessageChannel API,提供私有通信通道
- 🚀 高性能:零拷贝消息传输,低延迟通信
- 🛡️ 安全防护:Origin 验证、命名空间隔离、消息格式验证
- 🔧 简单易用:统一的 API 接口,自动处理连接时序
- 📊 监控统计:内置消息统计、连接状态监控、Ping 测试
- 🔄 自动重连:连接断开时自动重连机制
- 📝 完整日志:详细的调试日志和错误追踪
- 🎯 TypeScript:完整的类型定义支持
📦 安装
npm install fast-bridge🚀 快速开始
宿主页面 (Host)
import { FastBridge } from "fast-bridge";
// 创建 iframe
const iframe = document.createElement("iframe");
iframe.src = "./client.html";
document.body.appendChild(iframe);
// 创建桥接器
const bridge = new FastBridge({
namespace: "my-app",
debug: true,
iframe: iframe,
});
// 注册方法供客户端调用
bridge.register("getUserInfo", async (params) => {
return {
name: "John",
age: 25,
...params,
};
});
// 监听客户端事件
bridge.on("userLogin", (data) => {
console.log("用户登录:", data);
});
// 初始化连接
await bridge.init();
// 调用客户端方法
const result = await bridge.call("getData", { id: 123 });
console.log("客户端返回:", result);客户端页面 (Client)
import { FastBridge } from "fast-bridge";
// 创建桥接器
const bridge = new FastBridge({
namespace: "my-app",
debug: true,
});
// 注册方法供宿主调用
bridge.register("getData", async (params) => {
return {
data: "some data",
timestamp: Date.now(),
...params,
};
});
// 监听宿主事件
bridge.on("updateUI", (data) => {
console.log("收到宿主更新:", data);
});
// 初始化连接
await bridge.init();
// 调用宿主方法
const userInfo = await bridge.call("getUserInfo", { includeAvatar: true });
console.log("用户信息:", userInfo);📚 API 文档
FastBridge 构造函数
interface BridgeOptions {
namespace?: string; // 命名空间,默认为 "default"
debug?: boolean; // 是否开启调试日志,默认为 false
iframe?: HTMLIFrameElement; // iframe 元素,传入表示宿主页面
security?: {
strictOrigin?: boolean; // 是否严格验证源,默认为 true
allowedOrigins?: string[]; // 允许的源列表
};
}核心方法
init(): Promise<void>
初始化连接,自动处理所有时序问题。
register(methodName: string, handler: MethodHandler): void
注册方法供对方调用。
bridge.register("calculate", async (params) => {
const { a, b, operation } = params;
return eval(`${a} ${operation} ${b}`);
});call<T>(methodName: string, params?: any): Promise<T>
调用对方注册的方法。
const result = await bridge.call("getUserInfo", { includeAvatar: true });emit(eventName: string, data?: any): void
发送事件给对方。
bridge.emit("userLogin", { userId: 123, timestamp: Date.now() });on(eventName: string, callback: EventCallback): void
监听对方发送的事件。
bridge.on("updateUI", (data) => {
console.log("收到UI更新:", data);
});连接管理
getConnectionStatus(): boolean
获取当前连接状态。
getConnectionInfo(): ConnectionInfo
获取详细的连接信息。
onConnectionChange(callback: (connected: boolean) => void): void
监听连接状态变化。
reconnect(): Promise<void>
重新连接。
disconnect(): void
断开连接。
监控和统计
ping(): Promise<number>
Ping 测试,返回延迟时间(毫秒)。
getMessageStats(): MessageStats
获取消息统计信息。
const stats = bridge.getMessageStats();
console.log(`发送: ${stats.sent}, 接收: ${stats.received}, 错误: ${stats.errors}`);resetMessageStats(): void
重置消息统计。
🔒 安全特性
默认安全策略
- ✅ 严格源验证:只允许同源和 iframe 源通信
- ✅ 命名空间隔离:不同命名空间的消息完全隔离
- ✅ 消息格式验证:所有消息都经过格式验证
- ✅ Origin 验证:验证所有 postMessage 的来源
自定义安全策略
// 严格模式(默认)
const bridge = new FastBridge({
namespace: "my-app",
iframe: iframe,
security: {
strictOrigin: true, // 只允许同源和 iframe 源
},
});
// 宽松模式
const bridge = new FastBridge({
namespace: "my-app",
iframe: iframe,
security: {
strictOrigin: false,
allowedOrigins: ["https://trusted-site.com", "https://api.example.com"],
},
});🚀 连接特性
- ⏱️ 连接时间:1-2 秒(等待 iframe 完全准备就绪)
- ✅ 稳定可靠:确保连接建立后再进行通信
- 🔄 自动重连:连接断开时自动重连机制
- 📊 连接监控:实时监控连接状态和消息统计
🎯 使用场景
1. 微前端架构
// 主应用
const bridge = new FastBridge({
namespace: "main-app",
iframe: microAppIframe,
});
// 子应用
const bridge = new FastBridge({
namespace: "main-app",
});2. 第三方组件集成
// 宿主页面
const bridge = new FastBridge({
namespace: "widget",
iframe: thirdPartyWidget,
});
// 第三方组件
const bridge = new FastBridge({
namespace: "widget",
});3. 跨域通信
// 需要配置允许的源
const bridge = new FastBridge({
namespace: "cross-origin",
iframe: crossOriginIframe,
security: {
strictOrigin: false,
allowedOrigins: ["https://trusted-domain.com"],
},
});🔧 开发
安装依赖
npm install开发模式
npm run dev构建
npm run build运行示例
# 启动开发服务器
npm run dev
# 访问示例页面
open http://localhost:5173/examples/basic/host.html📊 性能对比
| 特性 | Fast Bridge | postMessage | CustomEvent | | -------- | -------------- | ------------- | ----------- | | 通信方式 | MessageChannel | postMessage | CustomEvent | | 安全性 | 🔒 私有通道 | ⚠️ 可被监听 | ⚠️ 同域限制 | | 性能 | 🚀 零拷贝 | 🐌 序列化开销 | 🚀 零拷贝 | | 跨域支持 | ✅ 支持 | ✅ 支持 | ❌ 不支持 | | 自动重连 | ✅ 支持 | ❌ 不支持 | ❌ 不支持 | | 连接监控 | ✅ 支持 | ❌ 不支持 | ❌ 不支持 |
🤝 贡献
欢迎提交 Issue 和 Pull Request!
📄 许可证
MIT License
🙏 致谢
感谢所有为这个项目做出贡献的开发者!
