赞
踩
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>
提示:以下是实现的最终效果
提示:以下是在本地测试时遇到的一些问题,可供大家参考
- // 主要是因为本地开发环境自动获取文件问题,可在主进程中增加如下判断即可:
- # background.js
- ...
- let checkForUpdates = () => {
- // 本地开发环境,改变dev-app-update.yml地址
- // 请注意build后生成的yml文件名
- if (process.env.NODE_ENV === 'development') {
- autoUpdater.updateConfigPath = path.join(__dirname, 'latest.yml')
- }
- ...
- // vue.config.js
- pluginOptions: {
- electronBuilder: {
- nodeIntegration: true,
- preload: 'src/preload.js',
- builderOptions: {
- nsis: {
- + perMachine: true
- }
- }
- }
- }
-
- // packages.json
- {
- ...
- "author": "XXX"
- ...
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。