使用electron开发桌面应用对于前端来说是比较新的领域。通常web端实现应用的更新比较简单,因为用户访问web端的网页都是通过浏览器访问,输入网址后,找到对应服务器的资源然后返回给用户,所以我们更新应用只需要替换服务器端的代码就可以。但是对于客户端,大多数资源都是在本地的,没有网络也是可以打开,只是和网络交互的接口没有数据而已。
所以桌面应用程序更新需要用户在应用开始时检测更新,用户决定是否更新替换当前应用。
electron-updater实现应用更新的步骤:
1、npm install electron-updater --save
这里不能使--save-dev因为该插件在程序运行时需要。
2、在electron程序入口文件main.js中加入如下配置
ipcMain.on('update', (e, arg)=>{
updateHandle();
})
// 检测更新,在你想要检查更新的时候执行,renderer事件触发后的操作自行编写
function updateHandle(){
let message={
error:'检查更新出错',
checking:'检查更新中……',
updateAva:'正在下载新版本……',
updateNotAva:'现在已是最新版本',
};
//如下应用程序的路径请自行替换成自己应用程序的路径
let updateFeedUrl='http://<ip>:<port>/download/win/';
if (process.platform == 'darwin') {
updateFeedUrl='http://<ip>:<port>/download/mac/';
}
autoUpdater.setFeedURL(updateFeedUrl);
autoUpdater.on('error', function(error){
sendUpdateMessage(message.error)
});
autoUpdater.on('checking-for-update', function() {
sendUpdateMessage(message.checking)
});
autoUpdater.on('update-available', function(info) {
sendUpdateMessage(message.updateAva)
});
autoUpdater.on('update-not-available', function(info) {
sendUpdateMessage(message.updateNotAva)
});
// 更新下载进度事件
autoUpdater.on('download-progress', function(progressObj) {
win.webContents.send('downloadProgress', progressObj)
})
autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
sendUpdateMessage('isUpdataNow');
ipcMain.on('updateNow', (e, arg) => {
autoUpdater.quitAndInstall();
})
});
//some code here to handle event
autoUpdater.checkForUpdates();
}
// 通过main进程发送事件给renderer进程,提示更新信息
function sendUpdateMessage(text){
win.webContents.send('message', text)
}
以上的流程是,渲染进程通知主进程进行更新检测 -> 主进程发起应用程序检测 -> 检测中 -> 下载应用 -> 替换应用 如果出问题都会走到error监听事件中
在渲染进程的需要检查更新的页面中,通知主进程进行更细的代码:
ipcRenderer.on("message", (event, text) => {
if(text == 'isUpdateNow'){
if(confirm('确认下载?')){
ipcRenderer.send('updateNow')
}
}
});
ipcRenderer.on("downloadProgress", (event, progressObj)=> {
console.log(progressObj);
});
ipcRenderer.send('update');
最后在打包时通过设置version参数自增,新版本号大于老版本号,如老版本号1.0.0,新版本2.0.0。这样就可以实现程序的自动更新
注意:自动更新只能用于electron打包安装版本的客户端,免安装版本不可实现自动更新!!
来源:oschina
链接:https://my.oschina.net/u/4313887/blog/3710832