Electron 自動更新


1. 安裝 electron-updater

npm i electron-updater --save-dev

2. 在package.json中

"build": {
    // ...
    "win": {
      "icon": "build/icons/icon.ico",
      "asar": false,
      "artifactName": "${productName}_${version}.${ext}"
    },
    "publish": [
      {
        "provider": "generic",
        "url": "http://127.0.0.1:8080" // 你的遠程服務器更新文件地址,暫時用本地服務模擬
      }
    ],
    "releaseInfo": {
      "releaseNotes": "" // 更新的內容,可不填
    }
  }

3. update.js

import {autoUpdater} from 'electron-updater'
import { ipcMain } from 'electron'

// 開始檢查更新
ipcMain.on('checkForUpdates', () => autoUpdater.checkForUpdates())

// 開始下載更新
ipcMain.on('downLoadUpdate', () => autoUpdater.downloadUpdate())

const updateHandle = (mainWindow, updateURL) => {
    const webContents = mainWindow.webContents
    const statusMessage = {
        error: {status: -1, msg: '檢測更新查詢異常'},
        checking: {status: 0, msg: '正在檢查應用程序更新'},
        updateAva: {status: 1, msg: '檢測到新版本,正在下載,請稍后'},
        updateNotAva: {status: 2, msg: '您現在使用的版本為最新版本,無需更新!'},
        downloadSuccess: {status: 2, msg: '下載新版成功'}
    }

    autoUpdater.autoDownload = false  // 手動指定下載
    autoUpdater.setFeedURL(updateURL)   // 更新包的地址,如 https://xxx.com/app/

    //執行自動更新檢查
    // autoUpdater.checkForUpdates()

    //更新錯誤
    autoUpdater.on('error', error => {
        console.log(error)
        webContents.send('uploadMessage', {payload: statusMessage.error, output: error})
    })

    //檢查中
    autoUpdater.on('checking-for-update', v => {
        console.log('檢查中')
        webContents.send('uploadMessage', {payload: statusMessage.checking, output: v})
    })

    //發現新版本
    autoUpdater.on('update-available', info => {
        console.log('發現新版本')
        webContents.send('uploadMessage', {payload: statusMessage.updateAva, output: info})
    })

    //當前版本為最新版本
    autoUpdater.on('update-not-available', info => {
        console.log('當前版本為最新版本')
        webContents.send('uploadMessage', {payload: statusMessage.updateNotAva, output: info})
    })

    // 更新下載進度事件
    autoUpdater.on('download-progress', progress => webContents.send('downloadProgress', progress))

    // 當下載完更新包后觸發
    autoUpdater.on('update-downloaded', info => {
        webContents.send('uploadMessage', {payload: statusMessage.downloadSuccess, output: info})
        autoUpdater.quitAndInstall()
    })
}


export default updateHandle

4. main進程中

const packInfo = require('../../package.json')
const [publish] = packInfo.build.publish


import updateHandle from './update'

// ....略
// createWindow時候
updateHandle(mainWindow, publish.url)

5. 渲染進程中(vue)

<template>
  <el-dialog
      style="pointer-events: none"
      :center="true"
      title="版本正在更新,請稍候..."
      :visible.sync="visible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
  >
    <div>
      <el-progress
          :text-inside="true"
          :stroke-width="24"
          :percentage="percentage"
          :show-text="true"
      />
    </div>
  </el-dialog>
</template>

<script>
const {ipcRenderer} = require('electron')

export default {
  name: "AutoUpdate",
  data() {
    return {
      visible: false,
      percentage: 0
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      ipcRenderer.send('checkForUpdates')
      ipcRenderer.on('uploadMessage', (event, args) => {
        console.log(args)
        const {payload} = args
        const {msg, status} = payload
        const handle = {
          '-1': () => {
            this.$message.error(msg)
          },
          '0': () => {
            this.$message.info(msg)
            /*正在檢測更新*/
          },
          '1': () => {
            this.$message.info(msg)
            /* 發送下載請求 */
            ipcRenderer.send('downLoadUpdate')
            this.visible = true
          },
          '2': () => {
            this.$message.info(msg)
            /*當前為最新版本*/
          },
          '3':() => {
            this.$message.success(msg)
          }
        }
        handle[`${status}`].call(this)
      })

      ipcRenderer.on('downloadProgress', (event, data) => {
        const {percent} = data
        this.percentage = Number.parseFloat((percent || 0).toFixed(2))
        if (percent >= 100) this.visible = false
      })
    }
  }
}
</script>

6. 測試

使用node靜態托管,nginx也可以

const express = require('express')
const app = express()

//設置跨域訪問
app.all('*', (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next()
})

app.use(express.static('D:/work/code/electron-print-web/build')) // 此處為打包后生成文件的絕對路徑

const server = app.listen(8080, 'localhost', () => {
    const host = server.address().address
    const port = server.address().port
    console.log('Example app listening at http://%s:%s', host, port)
})
  • 每次打包前去修改package.json中的version,打包完成后重啟已安裝的低版本程序,程序啟動后會自動更新至新版本


免責聲明!

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



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