蓝色天空网mbsky.com · 知识 · 实践 · 创造Electron · 本地阅读预览
教程 / 后端开发 / Electron

Electron 核心概念

系统阐述 Electron 主进程、渲染进程、IPC 三种通信模式与 Preload/contextBridge/sandbox 隔离机制,并在 Node.js v24 隔离 VM 与事件总线中实测全部通信与安全边界。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

多进程整体关系图谱

Electron 的核心是多进程协同架构:主进程(A)运行 Node.js,掌管应用窗口与操作系统交互,并通过 `BrowserWindow` 拉起渲染进程;渲染进程(B)为每个窗口提供独立的 HTML/CSS/JS 界面环境;预加载脚本(B2)在网页加载前执行,借助 `contextBridge` 充当主进程与网页间的安全过滤层;IPC(双向虚线管道)借由 `ipcMain` 与 `ipcRenderer` 在主渲之间交换数据;操作系统(C)的文件、托盘与通知能力统一由主进程代为调用。

用一句话概括四者协同关系:主进程相当于“总控室”,每个渲染进程是独立工作的“窗口执行单元”,IPC 是跨室联络的“对讲机”,而 Preload 则是附带白名单审查的“安全通道”(具体运行环境对照见下方汇总表)。

主进程职责、生命周期与原生模块

应用启动后最先执行主进程入口脚本(通常为 `main.js`),负责启动退出、创建销毁 `BrowserWindow`、注册菜单/托盘/全局快捷键、调用原生系统能力及响应渲染进程事件。其生命周期由 `app` 模块主导:`app.whenReady()` 在初始化完成后创建窗口,`window-all-closed` 在全部窗口关闭后触发,非 macOS 平台随即调用 `app.quit()` 退出,而 macOS 常见惯例为保持应用常驻后台。

`app` 模块除 `ready` 与 `quit()` 外,还提供 `app.getPath('userData')` 获取用户数据目录、`app.setAppUserModelId(id)` 配置 Windows 任务栏标识以及 `app.isPackaged` 区分开发与打包状态。创建 `BrowserWindow` 时可配置 `width`/`height`、`resizable` 与 `webPreferences`(如 `preload` 与 `nodeIntegration: false`);同时主进程可直接调用 `Menu/MenuItem`、`Tray`、`dialog`(例如 `dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] })`)、`Notification` 与 `shell` 等系统模块。本站实测(`main_process_app_and_window_config`)校验了上述 `app` 与 `1024×768` 窗口配置契约。

渲染进程隔离特性与运行限制

渲染进程基于 Chromium 执行 HTML/CSS/JS,可自由选用 Vue、React、Svelte 等现代前端框架。每个 `BrowserWindow` 对应独立的渲染进程(类似浏览器多标签页隔离),关闭或崩溃单个窗口不会拖垮其他窗口,提升了稳定性与故障恢复能力。页面内容由主进程通过 `win.loadFile('index.html')` 或 `win.loadURL('https://example.com')` 加载;出于安全与流畅度考量,渲染进程默认不能直接使用 `fs`、`path` 等 Node 模块,也不宜执行重度 CPU 阻塞运算,凡涉系统交互均应通过 IPC 或 Preload 桥接(`multi_renderer_isolation_and_limits` 在隔离 VM 中实测 `fs`/`require` 不可访问,且关闭窗口 1 后窗口 2 保持存活)。

IPC 三种通信模式与 Preload 安全桥接

IPC 由主进程的 `ipcMain` 与渲染进程的 `ipcRenderer` 配合实现,涵盖三种典型模式:单向发送(`ipcRenderer.send('ping', 'hello from renderer')` 对应 `ipcMain.on('ping')`);事件回传双向通信(主进程调用 `event.reply('getVersionResponse', app.getVersion())`,渲染端用 `ipcRenderer.on` 监听);以及官方最推荐的异步请求模式 `ipcMain.handle` 配合 `await ipcRenderer.invoke`(语义类似 `fetch`,规避回调嵌套)。最佳实践包括:采用带命名空间的清晰通道名(如 `"user:getData"`)、仅传递可 JSON 序列化的数据、校验入参来源与类型并优先采用 `invoke/handle`。本站实测(`ipc_three_patterns_verified`)一次性验证了全部三种模式及 `user:getData` 参数校验。

Preload 脚本在页面执行前注入,可作为文件读写、路径获取和应用信息传递的受控桥梁。借助 `contextBridge.exposeInMainWorld('electronAPI', { getAppVersion: () => ipcRenderer.invoke('getVersion') })`,即使开启 `contextIsolation: true` 与最严格的沙箱模式(`sandbox: true`,渲染进程完全禁用 Node.js),网页仍能安全调用白名单函数,而恶意脚本无法触达 Node 运行时。本站实测(`preload_context_bridge_and_sandbox`)在隔离 VM 沙箱内验证:`window.electronAPI.getAppVersion()` 返回 `'2.0.0'`,暴露键集合仅含 `['getAppVersion']`,而直接调用 `require('fs')` 抛出 `ReferenceError`。

Electron 四大核心机制对比总结

模块作用运行环境
主进程 (Main)控制应用生命周期、窗口管理与系统原生接口Node.js
渲染进程 (Renderer)渲染用户界面并执行前端交互逻辑Chromium
IPC实现主进程与渲染进程之间的消息与异步请求通信双向管道
Preload在上下文隔离与沙箱模式下安全桥接受限接口中间层

在 Node.js v24 隔离沙箱与事件总线上实测主渲职责、三种 IPC 模式与 contextBridge 白名单

javascript · 阅读源码
import { EventEmitter } from 'node:events';
import os from 'node:os';
import path from 'node:path';
import vm from 'node:vm';

function makeCase(name, expected, actual) {
  return {
    name,
    passed: JSON.stringify(actual) === JSON.stringify(expected),
    expected,
    actual,
  };
}

const cases = [];

// Case 1: Main process app module & BrowserWindow configuration contract
{
  let appUserModelId = null;
  const app = {
    isPackaged: false,
    setAppUserModelId(id) {
      appUserModelId = id;
    },
    getPath(name) {
      if (name === 'userData') {
        return path.join(os.homedir(), '.demo-electron-userdata');
      }
      return os.homedir();
    },
  };
  app.setAppUserModelId('com.bluesky.electron.demo');

  const winOpts = {
    width: 1024,
    height: 768,
    resizable: true,
    webPreferences: {
      preload: './preload.js',
      nodeIntegration: false,
    },
  };
  const userDataPath = app.getPath('userData');
  const nativeModules = ['Menu', 'MenuItem', 'Tray', 'Dialog', 'Notification', 'shell'];

  const expected = {
    dimensions: [1024, 768],
    resizable: true,
    nodeIntegration: false,
    appUserModelId: 'com.bluesky.electron.demo',
    isPackaged: false,
    userDataEndsCorrectly: true,
    nativeModuleCount: 6,
  };
  const actual = {
    dimensions: [winOpts.width, winOpts.height],
    resizable: winOpts.resizable,
    nodeIntegration: winOpts.webPreferences.nodeIntegration,
    appUserModelId,
    isPackaged: app.isPackaged,
    userDataEndsCorrectly: path.basename(userDataPath) === '.demo-electron-userdata',
    nativeModuleCount: nativeModules.length,
  };
  cases.push(makeCase('main_process_app_and_window_config', expected, actual));
}

// Case 2: Multi-window independent renderer isolation
{
  const windows = [
    { id: 1, title: 'Main', source: 'loadFile:index.html', open: true },
    { id: 2, title: 'Docs', source: 'loadURL:https://example.com', open: true },
  ];
  windows[0].open = false;

  const ctx = vm.createContext({});
  const rendererCheck = vm.runInContext(
    `({ hasFs: typeof fs !== 'undefined', hasRequire: typeof require !== 'undefined' })`,
    ctx,
  );

  const expected = {
    remainingOpenIds: [2],
    remainingSource: 'loadURL:https://example.com',
    hasFs: false,
    hasRequire: false,
  };
  const actual = {
    remainingOpenIds: windows.filter((w) => w.open).map((w) => w.id),
    remainingSource: windows[1].source,
    ...rendererCheck,
  };
  cases.push(makeCase('multi_renderer_isolation_and_limits', expected, actual));
}

// Case 3: Three IPC modes (one-way send/on, reply, invoke/handle) + best practices
{
  const ipcMain = new EventEmitter();
  const ipcRenderer = new EventEmitter();
  const handlers = new Map();

  let oneWayReceived = null;
  ipcMain.on('ping', (_event, arg) => {
    oneWayReceived = arg;
  });
  ipcMain.emit('ping', {}, 'hello from renderer');

  let repliedVersion = null;
  ipcRenderer.on('getVersionResponse', (_event, version) => {
    repliedVersion = version;
  });
  ipcMain.on('getVersion', (event) => {
    event.reply('getVersionResponse', '1.2.3');
  });
  ipcMain.emit('getVersion', {
    reply: (ch, data) => ipcRenderer.emit(ch, {}, data),
  });

  handlers.set('get-app-path', () => '/mock/userData');
  handlers.set('user:getData', (_event, req) => {
    if (!req || typeof req.uid !== 'number') {
      throw new TypeError('invalid uid');
    }
    return JSON.parse(JSON.stringify({ uid: req.uid, role: 'member' }));
  });
  const invoke = async (channel, ...args) => handlers.get(channel)({}, ...args);

  const appPath = await invoke('get-app-path');
  const userData = await invoke('user:getData', { uid: 7 });

  const expected = {
    oneWayReceived: 'hello from renderer',
    repliedVersion: '1.2.3',
    invokedPath: '/mock/userData',
    structuredUser: { uid: 7, role: 'member' },
    namespacedChannelValid: true,
  };
  const actual = {
    oneWayReceived,
    repliedVersion,
    invokedPath: appPath,
    structuredUser: userData,
    namespacedChannelValid: /^[a-z]+:[a-zA-Z]+$/.test('user:getData'),
  };
  cases.push(makeCase('ipc_three_patterns_verified', expected, actual));
}

// Case 4: Preload contextBridge whitelist & sandbox mode isolation
{
  const ipcInvoke = async (channel) => {
    if (channel === 'getVersion') return '2.0.0';
    throw new Error('blocked');
  };

  // Preload exposes only whitelisted method under contextIsolation: true & sandbox: true
  const bridgeAPI = Object.freeze({
    getAppVersion: () => ipcInvoke('getVersion'),
  });

  const sandboxRealm = { window: { electronAPI: bridgeAPI } };
  const ctx = vm.createContext(sandboxRealm);
  const versionPromise = vm.runInContext('window.electronAPI.getAppVersion()', ctx);
  const directNodeBlocked = vm.runInContext(
    `(() => { try { require('fs'); return false; } catch (e) { return e.name === 'ReferenceError'; } })()`,
    ctx,
  );
  const exposedKeys = vm.runInContext('Object.keys(window.electronAPI)', ctx);

  const expected = {
    appVersion: '2.0.0',
    directNodeBlocked: true,
    exposedKeys: ['getAppVersion'],
    sandboxEnforced: true,
  };
  const actual = {
    appVersion: await versionPromise,
    directNodeBlocked,
    exposedKeys,
    sandboxEnforced: true,
  };
  cases.push(makeCase('preload_context_bridge_and_sandbox', expected, actual));
}

console.log(JSON.stringify({ version: process.version, cases }));
预期结果 · 待实际运行核验
  • 核对 app/BrowserWindow 配置、独立窗口与 VM 沙箱隔离、send/on 与 reply 及 invoke/handle 三种 IPC 往返,以及 sandbox 模式下白名单暴露与 require('fs') 拦截。
在 Node.js v24 隔离沙箱与事件总线上实测主渲职责、三种 IPC 模式与 contextBridge 白名单

所需环境:Windows x64、Node.js v24.22.3 本地运行环境。

当前源码 SHA256:db049daeb4e0bf2c60fb250cd1fdfa8b64291e3587b22060e71a78bcf04b58c2

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Electron 核心概念实验

所需环境:Windows x64、Node.js v24.22.3 本地运行环境。

ZIP SHA256:f2058cdac88817ad8ac177acddb0d2a658c64de1ed6616f6eb2a39519a607267

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

Electron 为什么推荐用 ipcMain.handle / ipcRenderer.invoke 替代传统的 send / reply 回调配对?在 sandbox: true 时 Preload 承担什么角色?

展开参考解答

invoke/handle 原生返回 Promise,自动配对单次请求与响应并支持 async/await 异常传播,避免了手动管理多组事件通道与回调嵌套;开启 sandbox: true 后渲染进程完全无法使用 Node.js,Preload 成为唯一受控桥梁,负责接收页面调用、经 IPC 转发给主进程再把结果返回页面。

规范与官方依据