如何在 Vite 组件中通过 contextBridge 安全地调用主进程 API?
解读
这道题表面问“怎么调”,实则考察候选人是否真正理解 Electron 与 Vite 结合时的“安全边界”与“构建差异”。国内一线团队普遍把 Electron 主进程视为“内核”,渲染进程视为“外壳”,任何跨进程通信都必须经过 contextBridge 做“白名单”隔离。Vite 在渲染层只负责把代码转成 ESM,并不会帮你把 nodeIntegration 打开,也不会帮你把 preload 脚本打包好。因此,候选人必须同时给出三条路径:1. 让 Vite 正确编译 preload 脚本;2. 在 preload 里用 contextBridge 暴露有限 API;3. 在 Vue/React 组件里用 window.xxx 调用,并保证类型安全。面试官会顺着追问“如果 preload 体积过大如何拆包”“如何动态注入环境变量”“如何防止原型链污染”,答不上来就扣分。
知识点
- Electron 安全模型:contextIsolation 默认开启,渲染进程无法直接访问 require、ipcRenderer。
- contextBridge.exposeInMainWorld 只能暴露可克隆结构,函数必须做严格序列化。
- Vite 的“多入口”配置:build.rollupOptions.input 可额外指定 preload 脚本,输出格式必须为 cjs/iife,target 需设 node 环境。
- 类型声明:在 env.d.ts 中扩展 global 接口,使 window.ElectronAPI 获得 TypeScript 提示。
- 环境区分:开发阶段用 vite-plugin-electron 把 preload 脚本注入 dev-server,生产阶段走 files 协议读取 asar 包。
- 白名单机制:主进程通过 ipcMain.handle 注册频道,preload 只转发允许频道,拒绝通配符。
- 沙箱逃逸防护:禁止在 preload 里使用 remote、eval、Function 构造器;开启 sandbox 后 preload 也在独立上下文,需用 contextBridge 而非 window 直接挂载。
答案
-
项目结构
electron
├─ main // 主进程
├─ preload // 预加载脚本
└─ renderer // Vite 前端代码 -
配置 Vite 额外入口
// vite.config.ts
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
// vite-plugin-electron 可省略手写 dev 逻辑
],
build: {
rollupOptions: {
input: {
index: './index.html',
preload: './electron/preload/index.ts'
},
output: {
entryFileNames: (chunk) =>
chunk.name === 'preload' ? '[name].js' : 'assets/[name]-[hash].js'
}
},
target: 'node16' // preload 运行在 Node 上下文
}
}) -
编写 preload 脚本
// electron/preload/index.ts
import { contextBridge, ipcRenderer } from 'electron'const api = {
openFile: () => ipcRenderer.invoke('dialog:openFile'),
getAppVersion: () => ipcRenderer.invoke('app:version'),
onUpdateAvailable: (callback: (info: any) => void) => {
const wrapper = (_: any, info: any) => callback(info)
ipcRenderer.on('update-available', wrapper)
return () => ipcRenderer.removeListener('update-available', wrapper)
}
}contextBridge.exposeInMainWorld('ElectronAPI', api)
export type ElectronAPI = typeof api
-
类型声明
// renderer/env.d.ts
import type { ElectronAPI } from '../electron/preload/index'export interface Window {
ElectronAPI: ElectronAPI
} -
在 Vue 组件中使用
<script setup lang="ts"> import { onMounted, ref } from 'vue' const version = ref('') async function handleOpen() { const path = await window.ElectronAPI.openFile() console.log('选中文件', path) } onMounted(async () => { version.value = await window.ElectronAPI.getAppVersion() window.ElectronAPI.onUpdateAvailable((info) => { ElMessage.info(`发现新版本:${info.version}`) }) }) </script> -
主进程提供对应 handle
// electron/main/index.ts
import { ipcMain, dialog, app } from 'electron'ipcMain.handle('dialog:openFile', async () => {
const { canceled, filePaths } = await dialog.showOpenDialog({
properties: ['openFile']
})
return canceled ? null : filePaths[0]
})ipcMain.handle('app:version', () => app.getVersion())
-
打包验证
pnpm build
electron-builder --dir
用 asar 解压工具检查 preload.js 是否被正确打入 resources/app.asar/electron/preload/,且未被 tree-shaking 掉关键代码。
拓展思考
- 如果 preload 需要依赖第三方库(如 lodash-es),Vite 会把其打包成 ESM,但 Electron 运行时要求 CJS,可通过 rollup 插件 @rollup/plugin-commonjs 强制转码,或把依赖标记为 external 并在主进程提前安装。
- 当项目有多个渲染窗口,且每个窗口需要不同 API 子集时,可在 input 里再拆 preload-a、preload-b,利用 Vite 的 lib 模式分别输出,避免“一个超大 preload 全量暴露”。
- 为了做到“热重载 preload”,可在 dev 脚本里监听 preload 改动,调用 win.webContents.reload() 重新注入,避免重启整个 Electron 进程。
- 国内合规场景下,如果主进程需要访问本地数据库或加密机,务必在 ipcMain.handle 里再做一次权限校验,例如通过当前窗口的 session 分区判断来源,防止渲染进程被 XSS 后恶意调用。
- 未来 Electron 可能默认启用 sandbox + utilityProcess,preload 将彻底失去 Node 能力,需要提前把“文件读写”等能力上收到主进程或 utility 进程,preload 只做消息转发,保持架构平滑迁移。