窗口与 WebContents

本章目标

  • 掌握 BrowserWindow 的核心配置,尤其是影响首屏体验的选项。
  • 理解窗口与 webContents 的关系,能管理多窗口的生命周期与消息路由。
  • 会用 WebContentsView 组织多视图布局,替代已废弃的 BrowserView。
  • 能处理窗口崩溃、加载失败、导航劫持等异常场景。

窗口的基本结构

BrowserWindow 是主进程中的原生窗口对象,内部持有一个 webContents(渲染进程的控制器)。

  • BrowserWindow:窗口尺寸、位置、标题、菜单、显示/隐藏。
  • webContents:页面加载、导航、DevTools、与渲染进程通信。
  • 一个窗口对应一个 webContents;WebContentsView 可以在一个窗口内嵌入多个 webContents。

创建窗口的关键配置

1// src/main/windows/main-window.ts
2import { BrowserWindow } from 'electron';
3import path from 'node:path';
4
5export function createMainWindow(): BrowserWindow {
6  const win = new BrowserWindow({
7    width: 1280,
8    height: 800,
9    minWidth: 960,
10    minHeight: 600,
11    show: false,
12    backgroundColor: '#ffffff',
13    titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
14    webPreferences: {
15      preload: path.join(__dirname, '../preload.js'),
16      contextIsolation: true,
17      sandbox: true,
18      nodeIntegration: false,
19      spellcheck: false,
20    },
21  });
22
23  win.once('ready-to-show', () => {
24    win.show();
25  });
26
27  win.loadFile(path.join(__dirname, '../../renderer/index.html'));
28
29  return win;
30}

首屏体验相关的三个选项

选项作用建议
show: false创建时不显示窗口配合 ready-to-show 使用,避免白屏闪烁
backgroundColor窗口背景色设置为页面主背景色,减少首帧白闪
paintWhenInitiallyHidden隐藏时是否继续渲染首帧默认 true;设为 false 可省资源,但 ready-to-show 可能延迟

ready-to-show 在渲染进程完成首次绘制后触发,是显示窗口的最佳时机:

1win.once('ready-to-show', () => {
2  win.show();
3  // 需要进一步降低白屏时可配合透明度过渡
4});

如果页面加载很慢,也可以设置一个兜底定时器,避免用户长时间看不到窗口:

1const fallback = setTimeout(() => win.show(), 3000);
2win.once('ready-to-show', () => {
3  clearTimeout(fallback);
4  win.show();
5});

窗口生命周期

常用事件:

事件时机用途
ready-to-show首帧可显示显示窗口
focus / blur获得/失去焦点暂停动画、刷新数据
maximize / unmaximize最大化状态变化调整布局
enter-full-screen / leave-full-screen全屏切换隐藏自定义标题栏
close关闭前拦截未保存确认
closed已关闭清理引用、注销监听

close 与 closed 的区别很重要:

1win.on('close', (event) => {
2  if (hasUnsavedChanges()) {
3    event.preventDefault();
4    showSaveConfirmDialog();
5  }
6});
7
8win.on('closed', () => {
9  // 窗口已销毁,不能再调用 win.webContents
10  mainWindow = null;
11});

多窗口管理

不要在模块里散落 BrowserWindow 变量。用一个窗口注册表统一管理,避免泄漏与消息错投。

1// src/main/windows/registry.ts
2import { BrowserWindow, WebContents } from 'electron';
3
4const windows = new Map<number, BrowserWindow>();
5
6export function registerWindow(win: BrowserWindow): void {
7  windows.set(win.webContents.id, win);
8  win.on('closed', () => {
9    windows.delete(win.webContents.id);
10  });
11}
12
13export function getWindowByWebContents(wc: WebContents): BrowserWindow | undefined {
14  return windows.get(wc.id);
15}
16
17export function broadcast(channel: string, payload: unknown): void {
18  for (const win of windows.values()) {
19    if (!win.isDestroyed()) {
20      win.webContents.send(channel, payload);
21    }
22  }
23}
24
25export function closeAll(): void {
26  for (const win of windows.values()) {
27    if (!win.isDestroyed()) win.close();
28  }
29}

IPC 处理时通过 event.sender 反查窗口,而不是猜测「当前窗口」:

1ipcMain.handle('window:minimize', (event) => {
2  const win = BrowserWindow.fromWebContents(event.sender);
3  win?.minimize();
4});

用 WebContentsView 组织多视图

BrowserView 已被 WebContentsView 取代。WebContentsView 更底层、更灵活,配合 BaseWindow 或 BrowserWindow.contentView 使用。

1// src/main/windows/workspace-window.ts
2import { BrowserWindow, WebContentsView } from 'electron';
3import path from 'node:path';
4
5export function createWorkspaceWindow(): BrowserWindow {
6  const win = new BrowserWindow({
7    width: 1440,
8    height: 900,
9    show: false,
10    backgroundColor: '#f5f6f8',
11  });
12
13  const sidebar = new WebContentsView({
14    webPreferences: {
15      preload: path.join(__dirname, '../preload.js'),
16      contextIsolation: true,
17      sandbox: true,
18    },
19  });
20  sidebar.webContents.loadFile(path.join(__dirname, '../../renderer/sidebar.html'));
21
22  const content = new WebContentsView({
23    webPreferences: {
24      preload: path.join(__dirname, '../preload.js'),
25      contextIsolation: true,
26      sandbox: true,
27    },
28  });
29  content.webContents.loadFile(path.join(__dirname, '../../renderer/content.html'));
30
31  win.contentView.addChildView(sidebar);
32  win.contentView.addChildView(content);
33
34  const layout = (): void => {
35    const { width, height } = win.getContentBounds();
36    const sidebarWidth = 260;
37    sidebar.setBounds({ x: 0, y: 0, width: sidebarWidth, height });
38    content.setBounds({ x: sidebarWidth, y: 0, width: width - sidebarWidth, height });
39  };
40
41  layout();
42  win.on('resize', layout);
43  win.once('ready-to-show', () => win.show());
44
45  return win;
46}

使用 WebContentsView 的注意事项:

  1. 每个 View 都有独立渲染进程,数量越多内存越高,不要为每个小面板创建 View。
  2. View 不参与父窗口的 DOM 布局,需要手动调用 setBounds() 并监听 resize。
  3. View 的 webContents 需要单独处理导航、权限、崩溃事件。
  4. 关闭窗口时要移除子 View 并销毁对应的 webContents,否则会泄漏。

无边框窗口与自定义标题栏

1const win = new BrowserWindow({
2  width: 1200,
3  height: 800,
4  frame: false,
5  titleBarStyle: 'hidden',
6  trafficLightPosition: { x: 16, y: 16 }, // macOS
7});

页面中标记可拖拽区域:

1.titlebar {
2  -webkit-app-region: drag;
3  height: 40px;
4}
5
6.titlebar button {
7  -webkit-app-region: no-drag;
8}

平台差异:

平台建议
macOStitleBarStyle: 'hiddenInset',用 trafficLightPosition 调整红绿灯位置
Windowsframe: false + 自绘最小化/最大化/关闭按钮,注意高 DPI 下的点击区域
Linux不同桌面环境的窗口管理差异大,需要真机验证

透明窗口会引入合成开销与平台限制,非必要不要使用:

1new BrowserWindow({
2  transparent: true,
3  backgroundColor: '#00000000',
4  frame: false,
5});

窗口状态持久化

保存窗口位置与尺寸时,要处理多显示器拔插导致的越界。

1// src/main/windows/state.ts
2import { screen, BrowserWindow, Rectangle } from 'electron';
3import fs from 'node:fs';
4import path from 'node:path';
5import { app } from 'electron';
6
7type WindowState = {
8  bounds: Rectangle;
9  maximized: boolean;
10};
11
12function stateFile(): string {
13  return path.join(app.getPath('userData'), 'window-state.json');
14}
15
16export function loadWindowState(): Partial<WindowState> {
17  try {
18    const raw = fs.readFileSync(stateFile(), 'utf-8');
19    return JSON.parse(raw) as WindowState;
20  } catch {
21    return {};
22  }
23}
24
25export function saveWindowState(win: BrowserWindow): void {
26  const state: WindowState = {
27    bounds: win.getNormalBounds(),
28    maximized: win.isMaximized(),
29  };
30  fs.writeFileSync(stateFile(), JSON.stringify(state), 'utf-8');
31}
32
33export function ensureVisible(bounds: Rectangle): Rectangle {
34  const display = screen.getDisplayMatching(bounds);
35  const area = display.workArea;
36  const width = Math.min(bounds.width, area.width);
37  const height = Math.min(bounds.height, area.height);
38  const x = Math.min(Math.max(bounds.x, area.x), area.x + area.width - width);
39  const y = Math.min(Math.max(bounds.y, area.y), area.y + area.height - height);
40  return { x, y, width, height };
41}

创建窗口时应用:

1const saved = loadWindowState();
2const bounds = saved.bounds ? ensureVisible(saved.bounds) : { width: 1280, height: 800 };
3
4const win = new BrowserWindow({
5  ...bounds,
6  show: false,
7});
8
9if (saved.maximized) win.maximize();
10
11win.on('close', () => saveWindowState(win));

getNormalBounds() 返回窗口在最大化/全屏之前的尺寸,比 getBounds() 更适合持久化。

webContents 的关键能力

加载与失败处理

1win.webContents.on('did-fail-load', (_event, errorCode, errorDescription, validatedURL) => {
2  console.error('load failed', errorCode, errorDescription, validatedURL);
3  // 可以加载本地错误页
4  win.loadFile(path.join(__dirname, '../../renderer/error.html'));
5});
6
7win.webContents.on('did-finish-load', () => {
8  console.log('page loaded');
9});

导航与新窗口管控

渲染进程里的链接可能把整个应用导航到外部站点,必须拦截:

1import { shell } from 'electron';
2
3win.webContents.on('will-navigate', (event, url) => {
4  const allowed = new URL(url);
5  if (allowed.origin !== 'https://app.example.com') {
6    event.preventDefault();
7  }
8});
9
10win.webContents.setWindowOpenHandler(({ url }) => {
11  if (url.startsWith('https://')) {
12    shell.openExternal(url);
13  }
14  return { action: 'deny' };
15});

setWindowOpenHandler 返回 { action: 'allow' } 时应同时提供安全的 webPreferences,否则新窗口可能继承不安全配置。更稳妥的做法是统一拒绝,由主进程显式创建受控窗口。

渲染进程崩溃恢复

1win.webContents.on('render-process-gone', (_event, details) => {
2  console.error('renderer gone', details.reason, details.exitCode);
3
4  if (details.reason === 'crashed' || details.reason === 'oom') {
5    // 简单恢复策略:重新加载页面
6    win.webContents.reload();
7  } else {
8    // 其他原因(如 killed)不应无限重载
9  }
10});

需要注意:

  • reason 可能是 clean-exit、abnormal-exit、killed、crashed、oom、launch-failed、integrity-failure。
  • 对 oom 频繁重载可能形成崩溃循环,应加重试上限与降级策略。
  • render-process-gone 后不要继续向旧的 webContents 发送消息。

页面无响应

1win.webContents.on('unresponsive', () => {
2  console.warn('renderer unresponsive');
3});
4
5win.webContents.on('responsive', () => {
6  console.log('renderer responsive again');
7});

unresponsive 通常意味着渲染进程主线程被长任务占用。生产环境可以上报该事件,用于定位卡顿。

窗口与性能

窗口层面的性能影响主要有:

因素影响建议
透明窗口合成开销、GPU 内存增加非必要不用
大量 WebContentsView每个 View 独立进程与内存控制数量,复用 View
隐藏窗口继续渲染CPU/GPU 持续占用设置 backgroundThrottling: true
窗口频繁 resize触发布局与重绘布局节流、避免同步读取尺寸
首屏大背景图首帧绘制变慢用纯色背景 + 延迟加载图片
1new BrowserWindow({
2  webPreferences: {
3    backgroundThrottling: true, // 默认 true,后台窗口降低渲染频率
4  },
5});

如果应用需要在后台保持动画或音视频,可对特定窗口关闭节流,但要有明确理由。

本章小结

  • show: false + ready-to-show + backgroundColor 是首屏体验的标准组合。
  • 用注册表管理多窗口,通过 event.sender 路由消息,避免全局变量与泄漏。
  • 多视图场景使用 WebContentsView,注意独立进程成本与手动布局。
  • 必须拦截 will-navigate 与 setWindowOpenHandler,防止页面把应用导航到不可信站点。
  • render-process-gone 是渲染进程崩溃的统一入口,恢复策略要有上限。

参考资料