Electron 核心概念

app、BrowserWindow、webContents、进程模型、上下文隔离。

Beginner
Key Pointsapp 是应用本身,BrowserWindow 是窗口,webContents 是窗口里的网页;三者是主进程操作界面的抓手。

四个核心对象

ObjectRepresentsTypical use
app整个应用生命周期、单实例、开机自启
BrowserWindow一个原生窗口尺寸、标题、菜单、显示隐藏
webContents窗口里的页面加载 URL、执行 JS、发消息
session一个分区的存储与网络配置Cookie、缓存、代理、权限

app 的常用能力

JavaScript
const { app } = require('electron');

app.whenReady().then(() => { /* 可以创建窗口了 */ });

app.getVersion();               // package.json 里的 version
app.getName();
app.getPath('userData');        // 用户数据目录(存配置、数据库)
app.getPath('downloads');
app.setLoginItemSettings({ openAtLogin: true });   // 开机自启
app.quit();                     // 退出
app.exit(0);                    // 立即退出,不触发 before-quit

// 单实例:第二次启动时激活已有窗口
const gotLock = app.requestSingleInstanceLock();
if (!gotLock) {
  app.quit();
} else {
  app.on('second-instance', () => {
    const win = BrowserWindow.getAllWindows()[0];
    if (win) { if (win.isMinimized()) win.restore(); win.focus(); }
  });
}

userData is where config belongs: %APPDATA% on Windows, ~/Library/Application Support on macOS, ~/.config on Linux. Never write into the install directory — it may not be writable.

BrowserWindow 的常用方法

JavaScript
const win = new BrowserWindow({
  width: 1200, height: 800,
  minWidth: 800, minHeight: 600,
  frame: true,                 // false = 无边框,自己做标题栏
  show: false,                 // 先隐藏,ready-to-show 再显示,避免白屏闪烁
  backgroundColor: '#0f172a',
  webPreferences: { preload, contextIsolation: true, nodeIntegration: false }
});

win.once('ready-to-show', () => win.show());
win.loadFile('index.html');

win.setTitle('我的应用');
win.maximize();
win.setAlwaysOnTop(true);
win.hide();
win.webContents.send('ping', 'hello');       // 给页面发消息

show: false plus ready-to-show is the standard fix for the white flash on startup: by default the window appears blank before content renders, which looks broken.

进程模型

Text
Main process
 ├── Renderer process (窗口 1)
 ├── Renderer process (窗口 2)
 ├── GPU process
 └── Utility processes (网络、音频等)

One renderer per window: a crashed window leaves the others and the main process intact — the isolation Chromium's multi-process design provides. If the main process crashes, the whole app dies.

上下文隔离

JavaScript
// 默认且推荐:隔离
new BrowserWindow({
  webPreferences: { contextIsolation: true, nodeIntegration: false }
});

contextIsolation: true puts the preload script and the page in separate JS contexts, so the page monkey-patching Object.prototype cannot affect the bridge. Turning it off removes the wall and hands Node to the page.

Many old tutorials set nodeIntegration: true, a pre-2018 pattern. Today that lets any XSS in the page read arbitrary files and run arbitrary commands — a security audit will fail it outright.

Friends & Partners