Vue+Electron学习系列 (四) -- 自动更新进阶

Vue+Electron学习系列

1️⃣Vue+Electron学习系列 (一) -- 初识​​​​​​​

2️⃣ Vue+Electron学习系列 (二) -- 打包发布

3️⃣ Vue+Electron学习系列 (三) -- 自动更新

4️⃣ Vue+Electron学习系列 (四) -- 自动更新进阶



前言

说明:

此篇主要介绍并实现<kbd>Electron</kbd>通过渲染进程触发其更新操作流程。


一、主进程监听

// background.js
'use strict'

import { app, protocol, Menu, BrowserWindow, ipcMain } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'
const log = require('electron-log');
const { autoUpdater } = require("electron-updater")
const path = require('path')

//-------------------------------------------------------------------
// Logging
// +++ 此处为新增
// THIS SECTION IS NOT REQUIRED
//-------------------------------------------------------------------
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');

let win, webContents;


// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      // +++ 此处为新增 增加预加载脚本
      preload: path.join(__dirname, 'preload.js')
    },
    icon: `${__static}/icon.png`
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  // +++ 此处为新增
  webContents = win.webContents;

  win.on('closed', () => {
    win = null
  })
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

app.on('ready', async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    // Install Vue Devtools
    try {
      await installExtension(VUEJS_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  createWindow()
})

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

// +++ 以下皆为新增内容
// 主进程监听渲染进程传来的信息
ipcMain.on('update', (e, arg) => {
  console.log(arg);
  checkForUpdates();
});

let checkForUpdates = () => {
    // 配置安装包远端服务器
    // autoUpdater.setFeedURL(feedUrl);

    // 下面是自动更新的整个生命周期所发生的事件
    autoUpdater.on('error', function(message) {
        sendUpdateMessage('error', message);
    });
    autoUpdater.on('checking-for-update', function(message) {
        sendUpdateMessage('checking-for-update', message);
    });
    autoUpdater.on('update-available', function(message) {
        sendUpdateMessage('update-available', message);
    });
    autoUpdater.on('update-not-available', function(message) {
        sendUpdateMessage('update-not-available', message);
    });

    // 更新下载进度事件
    autoUpdater.on('download-progress', function(progressObj) {
        sendUpdateMessage('downloadProgress', progressObj);
    });
    // 更新下载完成事件
    autoUpdater.on('update-downloaded', function(event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
        sendUpdateMessage('isUpdateNow');
        ipcMain.on('updateNow', (e, arg) => {
            autoUpdater.quitAndInstall();
        });
    });

    //执行自动更新检查
    autoUpdater.checkForUpdates();
};

// 主进程主动发送消息给渲染进程函数
function sendUpdateMessage(message, data) {
  webContents.send('message', { message, data });
}

二、预加载脚本

// preload.js 如无此文件,手动创建即可
// 此目的为在渲染进程中无需引入ipcRenderer即可直接使用

import { ipcRenderer } from 'electron'
window.ipcRenderer = ipcRenderer

三、应用参数设置

// vue.config.js
module.exports = {
  //vue配置
  publicPath: process.env.NODE_ENV ==='production' ? './' : '/',

  pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
       // 增加预加载配置
      preload: 'src/preload.js',
      builderOptions: {
        //...
        // 此处省略打包参数
        //...  
        // 发布更新
        publish: [{
          provider: "generic",
          url: "http://localhost/releases/"          
        }]
      }
    }
  }
};

四、渲染进程触发更新检测

// 本人新建一个单独vue,处理
// version.vue
<template>
  <div class="version">
    <h1>当前版本:{{ version }}</h1>
    <button @click="autoUpdate()">获取更新</button>
    <ol id="content">
      <li>生命周期过程展示</li>
    </ol>
  </div>
</template>

<script>
import config from '../../package.json';
// 因为已经设置预加载脚本,所以渲染端可直接使用window.ipcRenderer
export default {
  data () {
    return {
      version: config.version
    }
  },
  mounted () {
    var ol = document.getElementById("content");
    window.ipcRenderer.on('message',(event,{message,data}) => {
        let li = document.createElement("li");
        li.innerHTML = message + " <br>data:" + JSON.stringify(data) +"<hr>";
        ol.appendChild(li);
        if (message === 'isUpdateNow') {
          if (confirm('是否现在更新?')) {
            window.ipcRenderer.send('updateNow', '立即更新');
          }
        }
    });
  },
  methods: {
    autoUpdate() {
      window.ipcRenderer.send('update', '更新...')
    }
  }
}
</script>
提示:以下是实现的最终效果

五、异常处理

提示:以下是在本地测试时遇到的一些问题,可供大家参考

1. Error: ENOENT, dev-app-update.yml not found in 

// 主要是因为本地开发环境自动获取文件问题,可在主进程中增加如下判断即可:
# background.js
...
let checkForUpdates = () => {
    // 本地开发环境,改变dev-app-update.yml地址
    // 请注意build后生成的yml文件名        
    if (process.env.NODE_ENV === 'development') {
        autoUpdater.updateConfigPath = path.join(__dirname, 'latest.yml')
    }    
...

2. Error: Unsupported provider: undefined

// vue.config.js
 pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      preload: 'src/preload.js',
      builderOptions: {
        nsis: {
+            perMachine: true
        }
      }
    }
 }

// packages.json
{
    ...
    "author": "XXX"
    ...
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bennett_G

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值