超详细!!!electron-vite-vue开发桌面应用之应用更新版本提示(十三)

云风网
云风笔记
云风知识库

当项目应用包更新后应该主动提示用户更新,这是采用electron-updater进行更新提示

一、安装依赖

npm i electron-updater  

二、配置安装包更新地址

electron-builder.json5添加配置

// 配置安装包更新地址
  publish: [
    {
      provider: "generic",
      url: "http://www.niech.cn/everyDayNote",
    },
  ]

三、新建封装版本管理工具electron/version.ts

import { autoUpdater } from 'electron-updater';
import { dialog, BrowserWindow } from 'electron';

const updateUrl = 'http://www.niech.cn/everyDayNote';

/**检测更新 */
export const checkUpdate = (win: BrowserWindow) => {
  console.log('开始检测');

  // 设置更新检测的资源路径,会检测对应路径下的 last.yaml文件中的版本信息 上线后确保该文件能正常访问
  if (process.platform == 'darwin') {
    autoUpdater.setFeedURL(`${updateUrl}/mac`);
    return;
  } else {
    autoUpdater.setFeedURL(`${updateUrl}/win`);
  }

  //检测更新
  autoUpdater.checkForUpdates();

  //监听'error'事件
  autoUpdater.on('error', err => {
    console.log('出错拉' + err);
    dialog.showErrorBox('更新出错拉!', err.message);
  });

  //监听'update-available'事件,发现有新版本时触发
  autoUpdater.on('update-available', () => {
    console.log('found new version');
    dialog.showMessageBox({
      message: '发现新版本,正在下载安装包'
    });
  });

  // 更新包下载百分比回调
  autoUpdater.on('download-progress', function (progressObj) {
    if (win) {
      win.webContents.send('download-progress', progressObj);
    }
  });

  //默认会自动下载新版本,如果不想自动下载,设置autoUpdater.autoDownload = false
  // autoUpdater.autoDownload = false;

  //监听'update-downloaded'事件,新版本下载完成时触发
  autoUpdater.on('update-downloaded', () => {
    dialog
      .showMessageBox({
        type: 'info',
        title: '应用更新',
        message: '需要退出程序才能安装新版本,是否安装?',
        buttons: ['是', '否']
      })
      .then(buttonIndex => {
        if (buttonIndex.response == 0) {
          //选择是,则退出程序,安装新版本
          autoUpdater.quitAndInstall();

        }
      });
  });
};

四、主进程main.ts调用更新校检

/**
* 版本更新检测
*/
ipcMain.handle("check-update",(e:any)=>{
  // 获取发送通知的渲染进程窗口
  const currentWin = getWindowByEvent(e);
  // 升级校验
  checkUpdate(currentWin);
});


/**
 * 通过窗口事件获取发送者的窗口
 * @param event ipc发送窗口事件
 */
function getWindowByEvent(event: IpcMainEvent): BrowserWindow {
  const webContentsId = event.sender.id;
  for (const currentWin of BrowserWindow.getAllWindows()) {
    if (currentWin.webContents.id === webContentsId) {
      return currentWin;
    }
  }
  return null;
}

utils/electron.ts添加工具方法定义

/**
 * 新建窗口
 * @param path 路由地址
 */
export function openWindow(path: string) {
  window.ipcRenderer.invoke("open-win", path);
}
/**
 * 检查版本更新
 */
export function checkUpdate(){
  window.ipcRenderer.invoke("check-update");
}
export default {
  openWindow,
  checkUpdate
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值