@smd_npm/iframe-bridge
v0.2.2
Published
面向 iframe 外链应用的框架无关宿主连接 SDK
Readme
@smd_npm/iframe-bridge
面向 iframe 外链应用的框架无关宿主连接 SDK。它只接收宿主通过
postMessage 发送的初始化数据和事件,并公开当前主应用支持的类型契约,不会主动向宿主发送消息。
安装
npm install @smd_npm/iframe-bridge该包仅发布 ESM,运行时无第三方依赖,仅适用于浏览器环境。
当前数据契约
- 初始化数据
MainAppInitData:{ token: string } - 事件
MainAppEventMap:logout,事件数据为undefined
后续主应用增加数据或事件时,会在以上公开类型中统一补充,使用方无需自行猜测契约。
快速开始
import IframeBridge from '@smd_npm/iframe-bridge';
const bridge = new IframeBridge({
allowedDomains: ['example.com'],
});
bridge.onInit((data) => {
console.info(data.token);
});
bridge.on('logout', () => {
console.info('logout');
});默认协议为:
{
source: 'admin-main',
version: 1,
initType: 'MAIN_APP_INIT',
eventType: 'MAIN_APP_EVENT',
childSource: 'iframe-bridge',
childEventType: 'IFRAME_BRIDGE_CHILD_EVENT',
}可以通过 protocol 覆盖任意字段:
const bridge = new IframeBridge({
allowedDomains: ['example.com'],
protocol: {
source: 'custom-host',
initType: 'IFRAME_BRIDGE_INIT',
eventType: 'IFRAME_BRIDGE_EVENT',
},
});iframe 高度上报
iframe 子应用可以主动向主应用上报内容高度,主应用监听后动态设置 <iframe> 高度。SDK 会优先使用构造时传入的 parentOrigin;如果未传入,则会在收到第一条合法主应用消息后缓存 event.origin,后续上报只发给该 origin。
const bridge = new IframeBridge({
allowedDomains: ['example.com'],
});
bridge.onInit(() => {
bridge.reportHeight();
});
const stopAutoResize = bridge.startAutoResize({
minHeight: 200,
maxHeight: 3000,
throttleMs: 100,
});autoResize 默认开启。如果需要自定义边界和节流参数,可以传入配置对象;如果不需要自动高度监听,可以显式传入 autoResize: false。
如果需要在主应用初始化消息到达前上报高度,可以显式指定 parentOrigin:
const bridge = new IframeBridge({
allowedDomains: ['example.com'],
parentOrigin: 'https://main.example.com',
});
bridge.reportHeight();iframe 发送给主应用的默认消息格式为:
{
source: 'iframe-bridge',
type: 'IFRAME_BRIDGE_CHILD_EVENT',
version: 1,
event: 'resize',
data: {
height: 860,
reason: 'observer',
},
}主应用侧仍需校验 event.source === iframe.contentWindow、event.origin、协议字段和 height 数值边界,再更新 iframe 样式。
API
data: 最近一次初始化数据,尚未初始化时为undefined。state:idle | waiting | initialized | destroyed。ready(): 等待下一次合法初始化;已初始化时立即返回最近数据。onInit(listener): 监听每次初始化,返回取消函数。on(event, listener): 监听指定事件,返回取消函数。once(event, listener): 只监听指定事件一次。onAny(listener): 监听所有合法事件。reportHeight(height?, options?): 主动向主应用上报 iframe 高度;没有安全目标 origin 时返回false。startAutoResize(options?): 自动监听内容高度变化并上报,返回取消函数。autoResize: 构造配置,默认开启;支持false、true或startAutoResize同款配置对象。start(): 开始监听,重复调用无副作用。stop(): 暂停监听,之后可以重新启动。destroy(): 永久销毁,清空订阅并拒绝未完成的ready()。
默认 autoStart 为 true。SSR 项目必须在浏览器入口或组件挂载阶段创建实例。
消息格式
初始化消息:
{
source: 'admin-main',
type: 'MAIN_APP_INIT',
version: 1,
data: {
token: 'current-token',
},
}事件消息:
{
source: 'admin-main',
type: 'MAIN_APP_EVENT',
version: 1,
event: 'logout',
}TypeScript 类型会提示当前支持的 token 和 logout。SDK 在运行时只校验消息信封,不校验业务
data 的内部结构;高安全业务应在回调中执行自己的运行时校验。
安全约束
消息必须同时满足:
event.source === window.parent。event.origin的主机名与allowedDomains完全一致,或是其子域名。source、version和type与协议配置一致。
allowedDomains 只接受不含协议、路径和端口的主机名。第一版不使用 Public
Suffix List,因此禁止配置 com、cn、com.cn、net、org 等公共后缀。
开发
npm test
npm run test:coverage
npm run typecheck
npm run build