4.0 KiB
4.0 KiB
Electron 项目开发方案
1. 项目目标
- 使用 Electron 开发一个桌面“框架程序”
- 主程序启动后自动打开指定 Web 应用(示例:
https://www.baidu.com) - 程序窗口自动全屏并隐藏菜单栏
- 支持在 Windows 与 Ubuntu 22 上打包与运行
2. 技术栈与工具
- 核心:
Electron - 打包:
electron-builder - 运行环境:
Node.js LTS(建议 18 或 20) - 版本管理:
npm
3. 环境准备
- 通用:安装 Node.js LTS
- Windows:建议安装 Git;如需原生模块构建,安装 Visual Studio Build Tools
- Ubuntu 22:
sudo apt updatesudo apt install -y build-essential libarchive-tools rpm xz-utils libfuse2
4. 目录结构(最小可运行)
项目根目录/
├─ main.js
└─ package.json
5. 初始化步骤
- 在项目根执行:
npm init -ynpm i -D electron electron-builder
- 准备主进程入口文件
main.js与打包配置package.json
6. 核心实现
6.1 主进程入口:main.js
const { app, BrowserWindow } = require('electron')
function createWindow() {
const win = new BrowserWindow({
fullscreen: true,
autoHideMenuBar: true,
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
sandbox: true
}
})
win.loadURL('https://www.baidu.com')
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})
6.2 打包与运行配置:package.json
{
"name": "electron-webshell",
"version": "0.1.0",
"main": "main.js",
"private": true,
"scripts": {
"start": "electron .",
"build": "electron-builder",
"build:win": "electron-builder --win",
"build:linux": "electron-builder --linux"
},
"devDependencies": {
"electron": "^31.2.0",
"electron-builder": "^24.9.4"
},
"build": {
"appId": "com.example.webshell",
"productName": "WebShell",
"files": [
"main.js",
"package.json"
],
"win": {
"target": ["nsis"],
"artifactName": "${productName}-Setup-${version}-${arch}.exe"
},
"linux": {
"target": ["AppImage", "deb"],
"category": "Utility",
"artifactName": "${productName}-${version}-${arch}.${ext}"
}
}
}
7. 开发与调试
- 启动开发模式:
npm start - 验证:程序启动后是否全屏、是否自动打开
https://www.baidu.com
8. 打包与发布
8.1 Windows 打包
- 在 Windows 上执行:
npm run build:win - 产物位置:
dist/WebShell-Setup-<version>-<arch>.exe - 安装并运行验证:全屏展示且加载指定网页
8.2 Ubuntu 22 打包
- 在 Ubuntu 22 上执行:
npm ci - 执行打包:
npm run build:linux - 产物位置:
dist/WebShell-<version>-<arch>.AppImagedist/WebShell-<version>-<arch>.deb
- 运行验证:
chmod +x dist/WebShell-<version>-<arch>.AppImage && ./dist/WebShell-<version>-<arch>.AppImage- 或安装
deb:sudo dpkg -i dist/WebShell-<version>-<arch>.deb
9. 安全与行为约束
- 保持
nodeIntegration: false,避免网页直接访问 Node 能力 - 使用
contextIsolation: true与sandbox: true,降低宿主风险 - 仅加载受信任站点;如需内网地址,将
loadURL改为目标内网 URL
10. 常见问题与建议
- 跨平台打包:建议在目标操作系统上本地打包(Windows 在 Windows,Linux 在 Ubuntu)
- 网络限制:如外网受限,改为内网地址;或将前端应用打包为本地资源并
loadFile - Ubuntu 22 下 AppImage 运行异常:安装
libfuse2 - 无边框与更强锁定:可将
fullscreen: true改为kiosk: true
11. 后续迭代方向
- 启动参数或配置文件化:支持自定义 URL、窗口模式
- 预加载脚本与白名单通信:在受控场景中安全地与网页交互
- 自动更新:集成更新服务以便统一升级