文档
Electron Hello World — 桌面应用
目标
创建一个完整的 Electron 桌面应用,展示主进程与渲染进程的基本通信。
完整代码
项目结构:
my-electron-app/
├── package.json
├── main.js # 主进程
├── preload.js # 预加载脚本
└── index.html # 渲染进程页面
package.json:
{
"name": "electron-hello",
"version": "1.0.0",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^28.0.0"
}
}
main.js(主进程):
const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
let mainWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 900,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true, // 安全:渲染进程无法直接访问 Node
nodeIntegration: false,
},
});
mainWindow.loadFile('index.html');
// 开发时可打开 DevTools
if (process.env.NODE_ENV === 'development') {
mainWindow.webContents.openDevTools();
}
}
// ===== 处理渲染进程的 IPC 请求 =====
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});
ipcMain.handle('show-message', async (event, message) => {
const { dialog } = require('electron');
dialog.showMessageBox(mainWindow, {
type: 'info',
title: '来自主进程',
message: message,
});
return '消息已显示';
});
app.whenReady().then(createWindow);
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
preload.js(预加载脚本):
const { contextBridge, ipcRenderer } = require('electron');
// 安全地向渲染进程暴露 API
contextBridge.exposeInMainWorld('electronAPI', {
getAppVersion: () => ipcRenderer.invoke('get-app-version'),
showMessage: (msg) => ipcRenderer.invoke('show-message', msg),
platform: process.platform,
});
index.html(渲染进程):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>Electron Hello World</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, 'Microsoft YaHei', sans-serif;
display: flex; flex-direction: column; align-items: center;
justify-content: center; height: 100vh;
background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
color: #eee;
}
h1 { font-size: 2.5rem; margin-bottom: 0.5rem; }
.subtitle { color: #aaa; margin-bottom: 2rem; }
button {
padding: 12px 28px; margin: 8px;
border: none; border-radius: 8px;
font-size: 1rem; cursor: pointer;
background: #7c4dff; color: white;
transition: transform 0.2s, background 0.2s;
}
button:hover { transform: translateY(-2px); background: #651fff; }
#version-info { margin-top: 1.5rem; color: #8f8; font-size: 0.9rem; }
</style>
</head>
<body>
<h1>🚀 Electron App</h1>
<p class="subtitle">跨平台桌面应用就这么简单</p>
<button id="btn-version">查看版本</button>
<button id="btn-message">显示消息框</button>
<div id="version-info"></div>
<script>
// 通过 preload 暴露的 API 访问 Electron 功能
document.getElementById('btn-version').addEventListener('click', async () => {
const version = await window.electronAPI.getAppVersion();
document.getElementById('version-info').textContent =
`当前版本:${version} | 平台:${window.electronAPI.platform}`;
});
document.getElementById('btn-message').addEventListener('click', async () => {
await window.electronAPI.showMessage('你好,来自渲染进程!');
});
</script>
</body>
</html>
运行步骤
npm install
npm start
预期输出
- 出现 900x600 桌面窗口,带渐变背景
- 点击"查看版本"按钮显示 Electron 版本号和当前平台
- 点击"显示消息框"按钮弹出系统原生对话框