1.安装electron-builder 和 electron-updater
npm i electron-updater electron-builder
2.package.json
"publish": [
{
"provider": "generic",
// 更新服务器地址
"url": "http://127.0.0.1:8089/updates/"
}
3.main.js
const { dialog } = require('electron');
// 引入自动更新
const { autoUpdater } = require('electron-updater')
// 自动更新检查
function checkForUpdates() {
// 检查新版本
autoUpdater.checkForUpdates()
// 监听更新事件
autoUpdater.on('checking-for-update', () => {
console.log('正在检查更新...')
})
autoUpdater.on('update-available', () => {
console.log('发现新版本...')
})
autoUpdater.on('update-not-available', () => {
console.log('当前已经是最新版本.')
})
autoUpdater.on('error', (error) => {
console.error('更新出错:', error)
})
autoUpdater.on('update-downloaded', (_) => {
console.log('下载完成,准备安装...')
// 下载完成后进行弹窗提示(也可以直接调用autoUpdater.quitAndInstall()进行更新)
showUpdateDialog()
})
}
// 创建弹窗提示
function showUpdateDialog() {
const focusedWindow = BrowserWindow.getFocusedWindow();
if (!focusedWindow) {
console.error('没有找到聚焦的窗口');
return;
}
dialog.showMessageBox(focusedWindow, {
type: 'info',
title: '更新可用',
message: '发现新版本,需要立即更新!',
buttons: ['立即更新'],
}).then(result => {
if (result.response === 0) {
/**
* 用户点击 "立即更新" 按钮,执行更新
* 形参:
* 参数1:仅在静默模式下运行安装程序。默认为false(windows下有效)。
* 参数2:即使是静默安装,也要在完成后运行应用程序。不适用于macOS。如果 参数1 设置为false,则忽略(在这种情况下,您仍然可以将autoRunAppAfterInstall设置为false以防止在完成后运行应用程序)
*/
autoUpdater.quitAndInstall(true, true);
}
});
}
// 部分 API 在 ready 事件触发后才能使用。
app.whenReady().then(() => {
createWindow()
// // 每隔一段时间自动检查更新
// setInterval(() => {
// checkForUpdates()
// }, 10 * 1000) // 10秒检查一次更新
// 启动时检查更新
checkForUpdates()
app.on('activate', function () {
// 通常在 macOS 上,当点击 dock 中的应用程序图标时,如果没有其他
// 打开的窗口,那么程序会重新创建一个窗口。
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})