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

此篇为实现渲染端的触发更新

主进程监听

// 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
//
// This logging setup is not required for auto-updates to work,
// but it sure makes debugging easier :)
//-------------------------------------------------------------------
autoUpdater.logger = log;
autoUpdater.logger.transports.file.level = 'info';
log.info('App starting...');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
// +++ 此处为新增webcontent
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: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      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', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow()
  }
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
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')
    }
    
    ...
}
  1.  Unsupported provider: undefined

         修改两处配置即可

# vue.config.js

 pluginOptions: {
    electronBuilder: {
      nodeIntegration: true,
      preload: 'src/preload.js',
      builderOptions: {

        nsis: {
+            perMachine: true
        }
      }
    }
 }



# packages.json

{
    ...
    "author": "XXX"
    ...
}
扫描二维码关注公众号,回复: 13302111 查看本文章

猜你喜欢

转载自blog.csdn.net/glx490676405/article/details/108651216