共计 2153 个字符,预计需要花费 6 分钟才能阅读完成。
在已有的 Electron 项目基础上,
- 添加一个按钮
- 点击按钮调用系统 API(例如打开文件对话框)
- (可选)简要说明如何集成 React 或 Vue
✅ 1. 添加按钮并调用系统 API
我们将使用 Electron 提供的 dialog 模块,在点击按钮时打开系统文件选择对话框。
🔧 步骤一:在 preload.js 中暴露安全 API
出于安全考虑,不能直接在渲染进程(HTML/JS)中使用 require('electron')。我们需要通过 contextBridge 安全地暴露有限功能。
修改 preload.js:
const {contextBridge, ipcRenderer} = require('electron')
contextBridge.exposeInMainWorld('electronAPI', {openFile: () => ipcRenderer.invoke('dialog:openFile')
})
contextBridge.exposeInMainWorld允许你在网页中通过window.electronAPI调用预定义的方法。
🔧 步骤二:在 main.js 中监听 IPC 事件
在主进程中处理文件对话框请求:
在 main.js 的顶部添加:
const {app, BrowserWindow, ipcMain, dialog} = require('electron')
在 app.whenReady() 之前(或任意位置)添加 IPC 处理逻辑:
ipcMain.handle('dialog:openFile', async () => {
const result = await dialog.showOpenDialog({properties: ['openFile']
})
return result.canceled ? null : result.filePaths[0]
})
🔧 步骤三:在 index.html 中添加按钮和 JS
修改 index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello Electron + API</title>
</head>
<body>
<h1>Electron 示例:打开文件 </h1>
<button id="open-file"> 选择文件 </button>
<p> 选中的文件路径:<span id="file-path"> 无 </span></p>
<script>
document.getElementById('open-file').addEventListener('click', async () => {const filePath = await window.electronAPI.openFile()
document.getElementById('file-path').innerText = filePath || '未选择文件'
})
</script>
</body>
</html>
注意:这段
<script>是在渲染进程中运行的,但通过preload.js安全地调用了主进程功能。
▶️ 运行测试
npm start
点击“选择文件”按钮,会弹出系统文件选择框,选中后路径会显示在页面上!
🌐 2. 集成前端框架(React / Vue)简要指南
Electron 本身不限制前端技术。你可以用任何前端框架构建 UI,然后让 Electron 加载它。
✅ 集成 React(使用 Vite 创建)
# 创建 React + Vite 项目(作为 Electron 的渲染层)npm create vite@latest react-app -- --template react
cd react-app
npm install
然后修改 Electron 的 main.js,让窗口加载开发服务器(开发时)或构建后的静态文件(生产时):
// 开发时(假设 React 运行在 http://localhost:5173)win.loadURL('http://localhost:5173')
// 生产时(构建后)win.loadFile(path.join(__dirname, '../react-app/dist/index.html'))
更推荐使用 Electron Forge 或 Vite + Electron 模板(如
electron-vite)来简化配置。
✅ 集成 Vue(使用 Vue CLI 或 Vite)
类似地:
npm create vue@3
cd my-vue-app
npm install
npm run dev # 启动开发服务器
Electron 主进程加载 http://localhost:5173(或 Vue 默认端口)。
📦 推荐项目模板(开箱即用)
- Electron + React + Vite:
https://github.com/cawa-93/vite-electron-builder - Electron + Vue + Vite:
https://github.com/electron-vite/electron-vite-vue
这些模板已配置好开发 / 构建流程、热重载、安全上下文等。
✅ 总结
| 功能 | 实现方式 |
|---|---|
| 添加按钮 | HTML + 原生 JS 或框架 |
| 调用系统 API | 通过 preload.js + ipcRenderer/ipcMain 安全通信 |
| 集成 React/Vue | 构建前端项目,Electron 加载其开发服务器或静态文件 |
正文完

