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

mpx-webview-bridge

v1.0.1

Published

Enterprise-grade cross-platform Mini Program WebView communication framework with TypeScript support, advanced error handling, and performance optimization

Readme

MPX

MPX Logo

🚀 跨平台小程序 WebView 通信库

npm version TypeScript License: MIT Build Status Coverage

✨ 特性

  • 🎯 统一 API - 一套代码,支持所有主流小程序平台
  • 🔄 双向通信 - H5 与小程序原生环境无缝交互
  • 💪 TypeScript - 完整的类型定义,开发体验更佳
  • 🛡️ 错误处理 - 完善的错误处理和重试机制
  • 高性能 - 优化的通信协议,支持并发控制
  • 🔧 可扩展 - 支持自定义适配器和插件
  • 📱 全平台 - 支持微信、支付宝、字节跳动、百度小程序
  • 🎨 零依赖 - 轻量级设计,无外部依赖

🚀 快速开始

安装

# npm
npm install mpx-webview-bridge

# yarn
yarn add mpx-webview-bridge

# pnpm
pnpm add mpx-webview-bridge

H5 端使用

import MPX from 'mpx-webview-bridge';

// 创建实例
const mpx = new MPX({
  debug: true,
  timeout: 10000
});

// 初始化
await mpx.initialize();

// 调用小程序方法
const systemInfo = await mpx.invoke('getSystemInfo');
console.log('系统信息:', systemInfo);

// 显示提示
await mpx.invoke('showToast', {
  title: '操作成功!',
  icon: 'success'
});

// 监听事件
mpx.on('pageShow', (data) => {
  console.log('页面显示事件:', data);
});

小程序端使用

// pages/webview/webview.js
import { MPXNativeBridge } from 'mpx-webview-bridge/native';

Page({
  onLoad() {
    // 创建桥接器
    this.bridge = new MPXNativeBridge(this);
    
    // 注册方法处理器
    this.bridge.registerMethod('getSystemInfo', async () => {
      return new Promise((resolve) => {
        wx.getSystemInfo({ success: resolve });
      });
    });
  },

  onMessage(e) {
    // 处理来自 H5 的消息
    this.bridge.handleMessage(e.detail.data);
  }
});

🎯 支持平台

| 平台 | 状态 | 版本要求 | 特殊说明 | |------|------|----------|----------| | 微信小程序 | ✅ 完全支持 | >= 2.4.0 | 支持所有基础 API | | 支付宝小程序 | ✅ 完全支持 | >= 2.0.0 | 支持支付宝特有 API | | 字节跳动小程序 | ✅ 完全支持 | >= 2.0.0 | 支持抖音、今日头条 | | 百度小程序 | ✅ 完全支持 | >= 3.0.0 | 支持百度智能小程序 |

📖 详细文档

核心概念

MPX WebView Bridge 基于适配器模式设计,为不同小程序平台提供统一的通信接口:

// 平台自动检测
const mpx = new MPX();
await mpx.initialize();

// 获取当前平台
const platform = mpx.getPlatform(); // 'wechat' | 'alipay' | 'bytedance' | 'baidu'

// 检查方法支持
if (mpx.isSupported('getLocation')) {
  const location = await mpx.invoke('getLocation');
}

配置选项

const mpx = new MPX({
  // 基础配置
  timeout: 10000,           // 请求超时时间(毫秒)
  debug: true,              // 开启调试模式
  
  // 重试配置
  retry: {
    times: 3,               // 重试次数
    delay: 1000,            // 重试延迟(毫秒)
    exponentialBackoff: true // 指数退避
  },
  
  // 性能配置
  maxConcurrentRequests: 10,        // 最大并发请求数
  enablePerformanceMonitoring: true, // 性能监控
  enableDataValidation: true,        // 数据验证
  
  // 错误处理
  errorHandler: (error) => {
    console.error('MPX 错误:', error);
    // 自定义错误处理逻辑
  }
});

方法调用示例

// 系统信息
const systemInfo = await mpx.invoke('getSystemInfo');

// UI 交互
await mpx.invoke('showModal', {
  title: '确认',
  content: '确定要执行此操作吗?'
});

// 页面导航
await mpx.invoke('navigateTo', {
  url: '/pages/detail/detail?id=123'
});

// 数据存储
await mpx.invoke('setStorage', {
  key: 'userInfo',
  data: { name: 'John', age: 30 }
});

// 网络请求
const response = await mpx.invoke('request', {
  url: 'https://api.example.com/data',
  method: 'POST',
  data: { key: 'value' }
});

// 设备功能
const location = await mpx.invoke('getLocation', {
  type: 'gcj02'
});

const images = await mpx.invoke('chooseImage', {
  count: 3,
  sourceType: ['album', 'camera']
});

事件系统

// 监听生命周期事件
mpx.on('pageShow', () => {
  console.log('页面显示');
});

mpx.on('pageHide', () => {
  console.log('页面隐藏');
});

// 监听系统事件
mpx.on('networkStatusChange', (status) => {
  console.log('网络状态变化:', status);
});

// 自定义事件
mpx.on('customEvent', (data) => {
  console.log('收到自定义事件:', data);
});

// 发送事件到小程序
mpx.emit('userAction', {
  action: 'click',
  target: 'button'
});

// 取消监听
mpx.off('pageShow', handler);

错误处理

try {
  const result = await mpx.invoke('getLocation');
} catch (error) {
  if (error.code === 'PERMISSION_DENIED') {
    console.log('用户拒绝了位置权限');
  } else if (error.code === 'TIMEOUT') {
    console.log('请求超时,请重试');
  } else {
    console.log('其他错误:', error.message);
  }
}

🔧 高级用法

自定义适配器

class CustomAdapter extends PlatformAdapter {
  name = 'custom';
  
  detect() {
    return typeof window.customPlatform !== 'undefined';
  }
  
  async initialize() {
    // 自定义初始化逻辑
  }
  
  async invoke(method, params) {
    // 自定义方法调用逻辑
  }
}

const mpx = new MPX({
  customAdapters: [CustomAdapter]
});

性能监控

// 开启性能监控
const mpx = new MPX({
  enablePerformanceMonitoring: true
});

// 获取性能指标
const metrics = mpx.getPerformanceMetrics();
console.log('平均响应时间:', metrics.averageResponseTime);
console.log('成功率:', metrics.successRate);

// 获取方法统计
const methodStats = mpx.getMethodStats();
console.log('方法调用统计:', methodStats);

调试工具

// 开启调试模式
const mpx = new MPX({ debug: true });

// 检查平台支持
const support = mpx.checkPlatformSupport([
  'getSystemInfo',
  'getLocation',
  'chooseImage'
]);

// 生成调试报告
const report = mpx.generateDebugReport();
console.log(report);

📚 API 文档

MPX 类方法

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | initialize(options?) | 初始化 MPX 实例 | MPXOptions? | Promise<void> | | invoke<T>(method, params?) | 调用小程序方法 | string, any? | Promise<T> | | on(event, callback) | 监听事件 | string, Function | void | | off(event, callback?) | 取消监听 | string, Function? | void | | emit(event, data?) | 发送事件 | string, any? | void | | getPlatform() | 获取当前平台 | - | Platform | | isSupported(method) | 检查方法支持 | string | boolean | | destroy() | 销毁实例 | - | void |

支持的小程序方法

基础 API

  • getSystemInfo - 获取系统信息
  • getNetworkType - 获取网络类型
  • getStorage / setStorage / removeStorage - 数据存储
  • request - 网络请求

UI 交互

  • showToast - 显示提示框
  • showModal - 显示模态对话框
  • showActionSheet - 显示操作菜单
  • showLoading / hideLoading - 显示/隐藏加载提示

页面导航

  • navigateTo - 跳转页面
  • redirectTo - 重定向页面
  • navigateBack - 返回页面
  • switchTab - 切换 Tab

设备功能

  • getLocation - 获取位置
  • chooseImage - 选择图片
  • previewImage - 预览图片
  • scanCode - 扫码
  • makePhoneCall - 拨打电话
  • setClipboardData / getClipboardData - 剪贴板操作

媒体功能

  • createInnerAudioContext - 音频播放(百度小程序)
  • createVideoContext - 视频播放(百度小程序)
  • getRecorderManager - 录音管理(百度小程序)

🧪 测试

# 运行所有测试
npm test

# 运行测试并生成覆盖率报告
npm run test:coverage

# 运行性能测试
npm run test:performance

# 运行压力测试
npm run test:stress

📦 构建

# 开发构建
npm run build:dev

# 生产构建
npm run build:prod

# 构建并分析包大小
npm run build:analyze

🤝 贡献

我们欢迎所有形式的贡献!请查看 贡献指南 了解详情。

开发流程

  1. Fork 本仓库
  2. 创建特性分支 (git checkout -b feature/amazing-feature)
  3. 提交更改 (git commit -m 'Add some amazing feature')
  4. 推送到分支 (git push origin feature/amazing-feature)
  5. 创建 Pull Request

开发环境

# 克隆仓库
git clone https://github.com/your-org/mpx.git
cd mpx

# 安装依赖
npm install

# 启动开发模式
npm run dev

# 运行测试
npm test

📄 许可证

本项目基于 MIT 许可证开源。

🙏 致谢

感谢所有为这个项目做出贡献的开发者!

📞 支持

如果您在使用过程中遇到问题,可以通过以下方式获取帮助:


⭐ 如果这个项目对您有帮助,请给我们一个 Star!

Made with ❤️ by Your Team