npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@bugfix2019/iframe-bridge

v0.0.3

Published

A universal iframe JavaScript bridge for secure communication

Readme

@bugfix2019/iframe-bridge

npm version License TypeScript Test Coverage

一个通用的 iframe JavaScript Bridge,用于浏览器环境下基于 postMessage 的安全通信。

注意:不支持 SSR,仅支持浏览器环境。

✨ 特性

  • 🎯 100% TypeScript - 完整类型定义
  • 测试覆盖率 - Vitest + v8 coverage,覆盖率按文件统计
  • 🚀 简单 API - 支持方法调用与事件
  • 🔒 Origin 校验 - 支持 allowedOrigins 白名单
  • 🔧 React Hook - 子路径导出 @bugfix2019/iframe-bridge/react

📦 安装

# npm
npm install @bugfix2019/iframe-bridge

# pnpm
pnpm add @bugfix2019/iframe-bridge

# yarn
yarn add @bugfix2019/iframe-bridge

前置要求:

  • 运行环境:浏览器,不支持 SSR
  • 开发/测试:Node.js >= 18.0.0

🚀 快速开始

父窗口(主页面):

import { createParentBridge } from '@bugfix2019/iframe-bridge';

const iframe = document.getElementById('myIframe') as HTMLIFrameElement;
const bridge = createParentBridge(iframe, 'https://child-domain.com', {
  debug: true,
  timeout: 5000,
  allowedOrigins: ['https://child-domain.com']
});

bridge.registerMethod('getUserInfo', async () => ({ id: 1, name: 'John Doe' }));

bridge.on('userAction', (data) => {
  console.log('userAction:', data);
});

const result = await bridge.call('childMethod', { param: 'value' });
console.log('child result:', result);

bridge.emit('parentEvent', { message: 'Hello from parent' });

子窗口(iframe 内):

import { createChildBridge } from '@bugfix2019/iframe-bridge';

const bridge = createChildBridge('https://parent-domain.com', { debug: true });

bridge.registerMethod('childMethod', async (params) => {
  console.log('childMethod params:', params);
  return { ok: true };
});

const userInfo = await bridge.call('getUserInfo');
console.log('userInfo:', userInfo);

bridge.on('parentEvent', (data) => console.log('parentEvent:', data));
bridge.emit('userAction', { action: 'click', target: 'button' });

React Hook:

import { useIframeBridge } from '@bugfix2019/iframe-bridge/react';

⚙️ 配置选项

BridgeOptions

export interface BridgeOptions {
  allowedOrigins?: string[];
  timeout?: number;
  debug?: boolean;
  messageValidator?: (message: any) => boolean;
}

Hook 参数:

  • mode: 'child':在 iframe 内自动连接 window.parent
  • mode: 'parent':需要传入 iframe 元素以连接 iframe.contentWindow

🧪 测试覆盖率

本仓库已配置 Vitest 覆盖率(@vitest/coverage-v8),输出目录为 coverage/

运行测试:

npm test

查看覆盖率报告:

npm run test:coverage

覆盖率(按文件):

| 文件 | 语句覆盖率 | 分支覆盖率 | 函数覆盖率 | 行覆盖率 | |------|-----------|-----------|-----------|---------| | src/bridge.ts | 90.32% | 77.08% | 100% | 90.32% | | src/index.ts | 100% | 100% | 100% | 100% | | src/react/useIframeBridge.ts | 84.14% | 88.88% | 100% | 84.14% | | src/react/index.ts | 100% | 100% | 100% | 100% | | 总计 | 89.12% | 82.19% | 100% | 89.12% |

纯类型文件 src/types.ts 不参与覆盖率统计。

🛠️ 开发

# 安装依赖
npm install

# 构建
npm run build

# 运行测试
npm test

# 查看覆盖率
npm run test:coverage

# 类型检查
npm run type-check

📦 发布到 npm

# 1. 确保构建成功
npm run build

# 2. 确保测试通过
npm test

# 3. 更新版本号
npm version patch
npm version minor
npm version major

# 4. 发布
npm publish --access public

📂 项目结构

iframe-bridge/
├── src/
│   ├── __test__/
│   │   ├── iframeBridge.__test__.ts
│   │   └── useIframeBridge.__test__.ts
│   ├── react/
│   │   ├── useIframeBridge.ts
│   │   └── index.ts
│   ├── bridge.ts
│   ├── types.ts
│   └── index.ts
├── dist/                           # 构建输出
├── coverage/                        # 运行 test:coverage 后生成
├── package.json
├── tsconfig.json
├── tsup.config.ts
├── vitest.config.ts
└── README.md

🤝 贡献

如需贡献:

  1. 修改/新增功能
  2. 增加/更新单元测试
  3. 运行 npm testnpm run test:coverage
  4. 更新 README

📄 许可证

MIT

👥 贡献者

感谢以下贡献者对本项目的贡献:

🔗 相关链接

❓ 常见问题

Q: 是否支持 SSR?

A: 不支持。该库依赖 windowpostMessage,仅支持浏览器环境。

Q: 如何限制允许通信的来源?

A: 在 BridgeOptions.allowedOrigins 里设置白名单(推荐始终设置)。

Q: 如何避免内存泄漏?

A: 在不再需要通信时调用 destroy();React 中使用 Hook 时,组件卸载会自动清理。


Made with ❤️ by Polaris