Electron 增加程序更新

环境:

        electron:26.1.0

        element-ui:2.15.13

        node:14.16.1

        electron-updater: 6.1.8

!!!理论来说这次功能升级跟环境是没有关系哈。!!!

过程

增加autoUpdate.js文件

// xiaoyi 1103914483@qq.com
// autoUpdater.js
const path = require("path");
const {autoUpdater} = require("electron-updater");

module.exports = (url , win,ipcMain,app) => {
    // console.log("url ==:", url);
    // console.log("win ==:", win);
    // console.log("NODE_ENV ==:", NODE_ENV);
    // console.log("NODE_ENV ==:", process.env.NODE_ENV);
    // console.log("__dirname ==:", __dirname);

    // 设置是否自动下载,默认是true,当点击检测到新版本时,会自动下载安装包,所以设置为false
    autoUpdater.autoDownload = false

    let message = {
        error: '检查更新出错',
        checking: '正在检查更新……',
        updateAva: '检测到新版本',
        updateNotAva: '现在使用的就是最新版本,不用更新'
    }

    // latest.yml 线上
    autoUpdater.updateConfigPath = path.join(
        __dirname,
        process.env.NODE_ENV === "development" ? "latest.yml" : "../app-update.yml"
    );
    // console.log("updateConfigPath ==:", autoUpdater._appUpdateConfigPath);

    // 设置更新源url
    autoUpdater.setFeedURL(url);

    autoUpdater.checkForUpdates();

    autoUpdater.on('error', function (err) {
        sendUpdateMessage('error',err||message.error)
    })
    autoUpdater.on('checking-for-update', function () {
        sendUpdateMessage('checking-for-update',message.checking)
    })
    // 版本检测结束,准备更新
    autoUpdater.on('update-available', function (info) {
        sendUpdateMessage('update-available',message.updateAva)
    })
    autoUpdater.on('update-not-available', function (info) {
        sendUpdateMessage('update-not-available',message.updateNotAva)
    })
    // 更新下载进度事件
    autoUpdater.on('download-progress', function (progressObj) {
        sendUpdateMessage('download-progress',progressObj.percent)
    })
    // 下载完成
    autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
        sendUpdateMessage('update-downloaded', '下载完成')
    })

    //没有新版本时
    autoUpdater.on("update-not-available", (_info) => {
        console.log("没有更新");
    });

    function sendUpdateMessage(name, text) {
        // 窗口对象自行修改
        win.webContents.send('UpdateMessage', {name, text})
    }


    // 触发更新检测
    ipcMain.on('checkForUpdates', () => {
        autoUpdater.checkForUpdates()
    })

    //  开始下载,通过渲染进程发起
    ipcMain.on('downloadUpdate', () => {
        autoUpdater.downloadUpdate()
    })

    //  下载完成,退出且重新安装
    ipcMain.on('updateSuccess', () => {
        // 加载更新程序
        autoUpdater.quitAndInstall()
        // 关闭当前electron
        app.quit()
    })


};

增加update.vue文件,同时需要再login页面引入update组件,以便触发更新操作,此位置可自定义操作。

<!-- xiaoyi 1103914483@qq.com-->
<template>
  <div>
    <el-dialog
        :visible.sync="modal"
        :title="'更新提醒(' + newVersion +')'"
        width="450px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :show-close="false"
        :destroy-on-close="true"
        top="25vh !important"
    >
      <p v-for='(item, index) in navJson' :key='index + "navJson"'>{{ index + 1 }}、{{ item }}</p>
      <p>{{ warning }}</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modal = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="download" size="mini">立即更新</el-button>
      </span>
    </el-dialog>

    <el-dialog
        :visible.sync="Progress"
        :mask-closable='false'
        :title="'正在更新(' + newVersion +')'"
        width="400"
        :closable='false'
    >
      <el-progress :text-inside="true"
                   :stroke-width="26"
                   :percentage="percent"></el-progress>
      <div slot="footer">

      </div>
    </el-dialog>
  </div>
</template>

<script>
const {ipcRenderer} = require("electron")
import axios from 'axios'

export default {
  name: "update",
  data() {
    return {
      modal: false,
      Progress: false,
      percent: 0,
      newVersion: '0.0.0',
      isOnMessage: false,
      warning: "",
      navJson: []
    }
  },
  created() {
    this.onUpdateExe()
  },
  methods: {
    onUpdateExe() {
      if (this.isOnMessage) return
      let that = this

      axios.get(process.env.VUE_APP_UPDATE_EXE_URL + "version.json").then(r => {
        if (r.status === 200) {
          let datum = r.data[0];
          let compareVersion = that.compareVersion(datum.version, process.env.VUE_APP_VERSION);

          if (compareVersion === 0) {
            // console.log("当前版本不需要更新")
          } else if (compareVersion === 1) {
            that.modal = true
            that.newVersion = datum.version;
            that.navJson = datum.notes;
            that.warning = datum.warning;
            that.isOnMessage = true
            // console.log('收到更新版本号', res, this.navJson)

            // 自动更新过程
            ipcRenderer.on('UpdateMessage', this.updateExe.bind(this))
            // 检查是否需要更新
            ipcRenderer.send('checkForUpdates')
          }
        }
      })

    },
    updateExe(e, data) {
      // 更新提示弹窗
      if (data.name == 'update-available') {
        console.log("update-available")
        this.modal = true
      } else if (data.name == 'download-progress') {    // 下载进度
        this.percent = Math.ceil(data.text)
      } else if (data.name == 'update-downloaded') {
        this.$message.success('下载完成,准备重启')
        setTimeout(() => {
          ipcRenderer.send('updateSuccess')
        }, 2000)
      }
    },
    //开始升级
    download() {
      this.Progress = true
      ipcRenderer.send('downloadUpdate')
    },
    compareVersion(version1, version2) {
      version1 = (version1[0] === 'v' || version1[0] === 'V') ? version1.substring(1, version1.length) : version1;
      version2 = (version2[0] === 'v' || version2[0] === 'V') ? version2.substring(1, version2.length) : version2;

      const newVersion1 = `${version1}`.split('.').length < 3 ? `${version1}`.concat('.0') : `${version1}`;
      const newVersion2 = `${version2}`.split('.').length < 3 ? `${version2}`.concat('.0') : `${version2}`;

      //计算版本号大小,转化大小
      function toNum(a) {
        const c = a.toString().split('.');
        const num_place = ["", "0", "00", "000", "0000"],
            r = num_place.reverse();
        for (let i = 0; i < c.length; i++) {
          const len = c[i].length;
          c[i] = r[len] + c[i];
        }
        return c.join('');
      }

      //检测版本号是否需要更新
      function checkPlugin(a, b) {
        const numA = toNum(a);
        const numB = toNum(b);
        return numA > numB ? 1 : numA < numB ? -1 : 0;
      }

      return checkPlugin(newVersion1, newVersion2);
    }
  }
}
</script>

<style lang="scss" scoped>
.ivu-modal-body {
  max-height: 120px;
  overflow-y: scroll;
  padding-top: 5px;

  p {
    line-height: 24px;
    height: 24px;
    font-size: 12px;

  }
}

.ivu-modal-footer {
  button:nth-child(1) {
    display: none;
  }
}
</style>
## 在main主线程js中增加即可 (我在package.js中指定的是background.js)
const Updater = require("./autoUpdate");


const win = new BrowserWindow({
...

Object.defineProperty(app, "isPackaged", {
        get() {
            return true;
        },
    });
Updater(process.env.VUE_APP_UPDATE_EXE_URL, win, ipcMain, app);
...
});

为了完美实现更新的过程我再项目中增加了一个version.json文件的版本控制,update.vue 会自动请求该文件获取进行对比当前是否需要更新。

[
  {
    "version": "v4.0.3",
    "git": "v1.1.0",
    "date": "2024-05-07",
    "warning": "...",
    "notes": [
      "增加自动更新程序",
    ]
  },
  {
    "version": "v4.0.2",
    "git": "v1.1.0",
    "date": "2024-05-06",
    "warning": "...",
    "notes": [
      "修复打包数据库无法本地读取",
      "修复本地端口无法修改"
    ]
  }
]

注:

  • 自行增加环境配置 process.env.VUE_APP_UPDATE_EXE_URL = https://xxx.xxx.xxx/xxx/
  • 通过electron打包后会在dist目录下生成 *.exe、latest.yml、version.json文件。当前目录下没有生成yml、和json可以参考以下配置。
  • 当打包成功后需要把*.exe、latest.yml、version.json 可将这三个文件放在可以通过连接访问的位置。
  • 自行安装electron-updater组件
## 其它主要配置已省略,请自行手动修改

electronBuilder:{  
        
    builderOptions: {
        publish: [
                    {
                        provider: "generic",
                        url: "http://xxxxxxx/download"
                    }
                ],
        extraResources: [
                {
                        from: "./version.json",
                        to: "../../version.json"
                 }
        ],
    
    }
}

配图:

因为之前已经更新过此版本,会在本地缓存此版本,所以不需要下载;可通过C:\Users\Administrator\AppData\Local\xxx\ 进行查看

至此完成所有electron操作过程,在网上也找了很多的资料都不太完整,通过自己方式进行了完善。

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值