Electron核心api详解

Electron 核心 API 按主进程 (Main Process)渲染进程 (Renderer Process)进程间通信 (IPC) 三大类划分,是开发跨平台桌面应用的基础。以下是最常用、最核心的模块与接口详解:


一、主进程 API (Main Process)

主进程是应用入口(main.js),负责生命周期、窗口、系统原生能力,可调用 Node.js 与全部 Electron API。

1. app ------ 应用生命周期总管

核心作用:控制启动、退出、系统路径、事件监听。

java 复制代码
const { app } = require('electron');

// 初始化完成(创建窗口必须在此后)
app.whenReady().then(() => { /* 创建窗口 */ });

// 所有窗口关闭(Windows/Linux 退出)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit();
});

// macOS 点击 Dock 图标重新激活
app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// 获取系统目录(用户数据、缓存、桌面等)
app.getPath('userData'); // 配置/数据存储
app.getPath('desktop');
app.getPath('downloads');

// 退出 / 重启
app.quit();
app.relaunch();
2. BrowserWindow ------ 窗口管理

核心作用:创建、控制原生窗口。

java 复制代码
const { BrowserWindow } = require('electron');

let mainWindow = new BrowserWindow({
  width: 1000,
  height: 700,
  title: 'Electron App',
  // 安全配置(必须)
  webPreferences: {
    nodeIntegration: false,       // 禁用 Node 直接注入
    contextIsolation: true,       // 开启上下文隔离
    preload: path.join(__dirname, 'preload.js') // 预加载脚本
  }
});

// 加载页面
mainWindow.loadFile('index.html');
// mainWindow.loadURL('https://example.com');

// 窗口操作
mainWindow.show();
mainWindow.hide();
mainWindow.maximize();
mainWindow.minimize();
mainWindow.close();

// 事件监听
mainWindow.on('closed', () => { mainWindow = null; });
3. webContents ------ 网页内容控制

核心作用:控制窗口内网页(调试、导航、打印、截屏)。

javascript 复制代码
// 打开开发者工具
mainWindow.webContents.openDevTools();

// 执行 JS
mainWindow.webContents.executeJavaScript('console.log("from main")');

// 导航
mainWindow.webContents.goBack();
mainWindow.webContents.goForward();

// 截屏
mainWindow.webContents.capturePage().then((img) => {
  fs.writeFileSync('screenshot.png', img.toPNG());
});
4. dialog ------ 原生对话框

核心作用:文件选择、保存、消息弹窗、错误提示。

javascript 复制代码
const { dialog } = require('electron');

// 打开文件选择
dialog.showOpenDialog({
  properties: ['openFile', 'multiSelections'],
  filters: [{ name: 'Images', extensions: ['jpg', 'png'] }]
}).then(result => {
  if (!result.canceled) console.log(result.filePaths);
});

// 保存对话框
dialog.showSaveDialog({ title: 'Save File' });

// 消息提示
dialog.showMessageBox({
  type: 'info',
  title: '提示',
  message: '操作成功',
  buttons: ['确定']
});
  • Menu:应用菜单、右键菜单
  • Tray:任务栏 / 状态栏图标(最小化到托盘)
6. globalShortcut ------ 全局快捷键
javascript 复制代码
// 注册全局快捷键(应用失焦也生效)
globalShortcut.register('CommandOrControl+Shift+X', () => {
  console.log('全局快捷键触发');
});
7. shell ------ 系统桌面集成
javascript 复制代码
const { shell } = require('electron');

shell.openExternal('https://electronjs.org'); // 打开默认浏览器
shell.showItemInFolder('C:/file.txt');       // 在资源管理器显示
shell.trashItem('path/to/file');             // 移到回收站
8. autoUpdater ------ 应用自动更新
  • 支持 macOS (Sparkle)、Windows (Squirrel) 自动更新

二、渲染进程 API (Renderer Process)

运行在 Chromium 中,默认不能直接访问 Node/Electron API ,必须通过 preload + contextBridge 安全暴露。

1. ipcRenderer ------ 向主进程发送消息
javascript 复制代码
// preload.js(安全暴露)
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
  sendMsg: (channel, data) => ipcRenderer.send(channel, data),
  onMsg: (channel, callback) => ipcRenderer.on(channel, callback)
});

// 渲染页面(index.html)
window.electronAPI.sendMsg('to-main', 'Hello from Renderer');
window.electronAPI.onMsg('to-renderer', (event, data) => {
  console.log(data);
});
2. clipboard ------ 系统剪贴板
javascript 复制代码
const { clipboard } = require('electron');
clipboard.writeText('复制内容');
clipboard.readText();
3. nativeTheme ------ 系统主题(深色 / 浅色模式)
javascript 复制代码
const { nativeTheme } = require('electron');
nativeTheme.themeSource = 'dark'; // 强制深色
console.log(nativeTheme.shouldUseDarkColors); // 当前是否深色
4. screen ------ 显示器信息
  • 获取屏幕尺寸、多显示器布局

三、进程间通信 (IPC)

主 ↔ 渲染 通信核心:ipcMain + ipcRenderer

1. 主进程监听(ipcMain)
javascript 复制代码
const { ipcMain } = require('electron');

// 单向接收
ipcMain.on('to-main', (event, arg) => {
  console.log(arg);
  // 回复
  event.reply('to-renderer', '收到: ' + arg);
});

// 双向调用(Promise)
ipcMain.handle('invoke-main', async (event, arg) => {
  return `处理: ${arg}`;
});
2. 渲染进程调用(ipcRenderer)
javascript 复制代码
// 单向发送
ipcRenderer.send('to-main', '数据');

// 双向调用(async/await)
const res = await ipcRenderer.invoke('invoke-main', '参数');

四、安全核心 API

  • contextBridge:安全暴露 API 到渲染层,避免直接访问 NodeElectron
  • webPreferences
    • nodeIntegration: false
    • contextIsolation: true
    • sandbox: true(进一步沙箱)

五、常用辅助 API

  • session:管理 Cookie、缓存、代理、网络请求
  • powerMonitor:监听系统睡眠 / 唤醒 / 电源状态
  • webFrame:渲染进程缩放、字体、JS 注入

六、API 分类速记

  • 生命周期app
  • 窗口BrowserWindowwebContents
  • 系统交互dialogshellclipboardtraymenuglobalShortcut
  • 通信ipcMainipcRenderercontextBridge
  • 渲染层webFramenativeThemescreen
相关推荐
渣渣xiong2 小时前
从零开始:前端转型AI agent直到就业第十二天-第十三天
前端·人工智能
05Nuyoah2 小时前
CSS 基础认知和基础选择器
前端·javascript·css·node.js
DanCheOo2 小时前
从单 Chat 到多 Agent 系统:AI 应用的架构演进路线
前端·agent
开开心心就好2 小时前
经典塔防游戏移植移动端随时畅玩
java·前端·科技·游戏·edge·django·pdf
We་ct2 小时前
前端包管理工具与Monorepo全面解析
前端·javascript·npm·pnpm·yarn·monorepo·包管理
六月的可乐2 小时前
AI Agent 架构设计与实践:React、Plan-Exec、Reflect 与混合模式(附开源代码)
前端·javascript·aigc
ZPC82102 小时前
moveit servo 发指令给real arm
java·前端·数据库
sunbin2 小时前
使用Playwright MCP实现UI自动化测试:从环境搭建到实战案例
前端
倚栏听风雨2 小时前
Node.js 子进程 fork 完全指南:从入门到踩坑全记录
前端