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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@chenpeiyuan/electron-message

v1.0.8

Published

一个用于 Electron 主进程和渲染进程之间通信的工具库。

Readme

electron-message

一个用于 Electron 主进程和渲染进程之间通信的工具库。

功能特点

  • 基于 IPC 的进程间通信
  • 支持服务注册和调用
  • 支持错误处理和类型验证
  • 简洁易用的 API 接口

安装

# 使用 npm
npm install @chenpeiyuan/electron-message

# 使用 yarn
yarn add @chenpeiyuan/electron-message

# 使用 pnpm
pnpm add @chenpeiyuan/electron-message

基本使用

1. 主进程 (main/index.js)

const { Main } = require('@chenpeiyuan/electron-message');

class MyMain extends Main {
  // 实现 getWebContents 方法,返回对应的 webContents
  protected getWebContents(reqEvent) {
    // 根据 reqEvent 中的信息返回对应的 webContents
    // 例如:return mainWindow.webContents;
    return { send: () => {} };
  }
}

// 创建实例
const main = new MyMain();

// 注册服务
main.addService('getUserInfo', async (userId) => {
  // 模拟获取用户信息
  return {
    id: userId,
    name: '测试用户',
    email: '[email protected]'
  };
});

// 初始化
main.init();

2. 预加载脚本 (preload.js)

const { expose } = require('@chenpeiyuan/electron-message');

// 暴露接口到渲染进程
expose('service');

3. 渲染进程 (renderer.js)

// 使用暴露的服务
async function getUserInfo() {
  try {
    const result = await window.service.invoke({
      api: 'getUserInfo',
      params: [123]
    });
    console.log('用户信息:', result.result);
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
}

// 调用服务
getUserInfo();

// 注册渲染进程服务
window.service.addService('showNotification', async (title, body) => {
  // 显示通知
  new Notification(title, { body });
  return '通知已显示';
});

API 文档

Main 类

构造函数

constructor(config?: Partial<Config>)
  • config: 配置对象,可选
    • reqChannel: 请求通道名称,默认为 'runService:req'
    • resChannel: 响应通道名称,默认为 'runService:res'
    • toErrorObject: 错误转换函数
    • log: 日志配置

方法

  • addService(key: string, service: Service): void - 添加单个服务
  • addServices(services: Record<string, Service>): void - 添加多个服务
  • getService(key: string): Service | undefined - 获取服务
  • delService(key: string): void - 删除服务
  • init(): void - 初始化
  • invoke(reqEvent: Omit<ServiceReqEvent, 'id' | 'reqAt'>): Promise<ServiceResEvent> - 调用服务

Preload 类

构造函数

constructor(config?: Partial<Config>)
  • config: 配置对象,同 Main 类

方法

  • addService(key: string, service: Service): void - 添加单个服务
  • addServices(services: Record<string, Service>): void - 添加多个服务
  • getService(key: string): Service | undefined - 获取服务
  • delService(key: string): void - 删除服务
  • init(): void - 初始化
  • invoke(reqEvent: Omit<ServiceReqEvent, 'id' | 'reqAt'>): Promise<ServiceResEvent> - 调用服务

expose 函数

function expose(key = 'service', config?: Partial<Config>): void
  • key: 暴露到渲染进程的全局对象名称,默认为 'service'
  • config: 配置对象,同 Main 类

类型定义

Service

type Service = (...params: Array<any>) => Promise<any>

ServiceReqEvent

interface ServiceReqEvent {
  id: string;
  api: string;
  dst: string;
  src: string;
  params: Array<any>;
  reqAt: number;
}

ServiceResEvent

interface ServiceResEvent {
  id: string;
  api: string;
  dst: string;
  src: string;
  error?: any;
  result?: any;
  reqAt: number;
  resAt: number;
}

示例项目

完整示例

主进程 (main.js)

const { app, BrowserWindow } = require('electron');
const { Main } = require('@chenpeiyuan/electron-message');
const path = require('path');

let mainWindow;

class MyMain extends Main {
  protected getWebContents(reqEvent) {
    return mainWindow.webContents;
  }
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });

  mainWindow.loadFile('index.html');

  // 注册服务
  const mainService = new MyMain();
  mainService.addService('getUserInfo', async (userId) => {
    return {
      id: userId,
      name: '测试用户',
      email: '[email protected]'
    };
  });
  mainService.init();
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

预加载脚本 (preload.js)

const { expose } = require('@chenpeiyuan/electron-message');
expose('service');

渲染进程 (index.html)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Electron Message Example</title>
  </head>
  <body>
    <h1>Electron Message Example</h1>
    <button id="getUserInfo">获取用户信息</button>
    <div id="result"></div>

    <script>
      document.getElementById('getUserInfo').addEventListener('click', async () => {
        const resultDiv = document.getElementById('result');
        try {
          const result = await window.service.invoke({
            api: 'getUserInfo',
            params: [123]
          });
          resultDiv.textContent = JSON.stringify(result.result, null, 2);
        } catch (error) {
          resultDiv.textContent = 'Error: ' + error.message;
        }
      });

      // 注册渲染进程服务
      window.service.addService('showNotification', async (title, body) => {
        new Notification(title, { body });
        return '通知已显示';
      });
    </script>
  </body>
</html>

测试

运行测试:

npm test

许可证

MIT