字节笔记本

2026年2月22日

Electron 更新窗口实现:electron-vue-cloud-music 源码解析

本文介绍 electron-vue-cloud-music 项目中的 updateWindow.js 文件,该文件实现了 Electron 应用的自动更新窗口功能,展示了如何创建一个模态更新提示窗口。

项目背景

electron-vue-cloud-music 是一个基于 Electron + Vue 开发的仿网易云音乐 Windows 客户端,在 GitHub 上已获得 2.5k+ stars。该项目展示了如何使用 Electron 构建跨平台桌面应用,结合 Vue.js 实现现代化的用户界面。

updateWindow.js 代码解析

该文件负责创建应用更新提示窗口,以下是完整代码:

```javascript import { LOAD_URL } from "./../config";

const miniWinURL = process.env.NODE_ENV === "development" ? `http://localhost:9080/#update\` : `${LOAD_URL}#update`;

const previewIcon = process.env.NODE_ENV === "development" ? "/images/tray.ico" : `${global.__images}/images/tray.ico`;

let updateWindow;

const createUpdateWindow = function (BrowserWindow) { if (updateWindow) return false;

let obj = { icon: previewIcon, height: 420, minHeight: 420, width: 340, minWidth: 340, show: false, frame: false, fullscreenable: false, resizable: process.env.NODE_ENV === "development", transparent: process.platform !== "linux", alwaysOnTop: true, webPreferences: { nodeIntegration: true, nodeIntegrationInWorker: true, webSecurity: false, navigateOnDragDrop: true, }, };

updateWindow = new BrowserWindow(obj); updateWindow.loadURL(miniWinURL);

updateWindow.on("ready-to-show", () => { updateWindow.show(); });

updateWindow.on("closed", () => { updateWindow = null; });

return updateWindow; };

export default createUpdateWindow; ```

核心功能分析

1. 环境判断与 URL 配置

```javascript const miniWinURL = process.env.NODE_ENV === "development" ? `http://localhost:9080/#update\` : `${LOAD_URL}#update`; ```

通过 `process.env.NODE_ENV` 判断当前环境:

  • 开发环境:使用本地开发服务器地址
  • 生产环境:使用打包后的 `LOAD_URL` 常量

2. 窗口配置选项

属性说明
`width` / `height`340 / 420窗口固定尺寸
`frame``false`无边框窗口,自定义标题栏
`transparent``true` (非 Linux)透明背景效果
`alwaysOnTop``true`窗口始终置顶
`resizable`开发环境为 `true`开发时可调整大小
`fullscreenable``false`禁止全屏

3. WebPreferences 配置

```javascript webPreferences: { nodeIntegration: true, // 启用 Node.js 集成 nodeIntegrationInWorker: true, // Worker 中可用 Node.js webSecurity: false, // 禁用同源策略(开发便利) navigateOnDragDrop: true, // 支持拖拽导航 } ```

4. 窗口生命周期管理

```javascript // 窗口准备就绪后显示(避免白屏) updateWindow.on("ready-to-show", () => { updateWindow.show(); });

// 窗口关闭时清理引用 updateWindow.on("closed", () => { updateWindow = null; }); ```

使用场景

该更新窗口适用于以下场景:

  1. 版本更新提示:检测到新版本时弹出提示
  2. 下载进度展示:显示更新包下载进度
  3. 更新确认对话框:让用户选择是否立即更新
  4. 强制更新提醒:重要版本强制用户更新

技术要点总结

  1. 单例模式:通过 `if (updateWindow) return false` 防止重复创建
  2. 环境适配:区分开发和生产环境的不同配置
  3. 平台兼容:Linux 平台禁用透明效果避免兼容问题
  4. 用户体验:`ready-to-show` 事件确保内容加载完成再显示窗口

项目链接

分享: