electron-updater實現electron應用程序更新


使用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打包安裝版本的客戶端,免安裝版本不可實現自動更新!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM