electron13+vue3 使用 electron-updater 自动更新

孙德宇
2023-12-01

完整代码地址

https://gitee.com/jddk/electron_vue_update.git

dist_electron中启动http-server服务

静态服务器用于下载.exe版本更新文件

background.js

"use strict";

import { app, protocol, BrowserWindow, ipcMain, ipcRenderer } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { autoUpdater } from "electron-updater";
import path from "path";
const isDevelopment = process.env.NODE_ENV !== "production";

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

let win;
async 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,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
      preload: path.join(__dirname, "preload.js")
    }
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await 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");
  }
}

//监听应用关闭
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 (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.on("ready", async () => {
  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", () => {
  checkUpdate();
});

function sendUpdateMessage(text) {
  win.webContents.send("message", text);
}

function checkUpdate() {
  if (process.platform == "darwin") {
    autoUpdater.setFeedURL("http://127.0.0.1:8080"); //设置要检测更新的路径
  } else {
    autoUpdater.setFeedURL("http://127.0.0.1:8080");
  }

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

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

  //监听'error'事件
  autoUpdater.on("error", (err) => {
    sendUpdateMessage(message.error);
  });

  autoUpdater.on("checking-for-update", function () {
    sendUpdateMessage(message.checking);
  });

  //监听'update-available'事件,发现有新版本时触发
  autoUpdater.on("update-available", () => {
    sendUpdateMessage(message.updateAva);
  });

  autoUpdater.on("update-not-available", function (info) {
    sendUpdateMessage(message.updateNotAva);
  });

  // 更新下载进度事件
  autoUpdater.on("download-progress", (progressObj) => {
    // console.log(progressObj);
    // win.webContents.send("downloadProgress", progressObj);
    // win.setProgressBar(progressObj.percent / 100);
    sendUpdateMessage(progressObj.percent / 100);
  });

  // 下载完成
  autoUpdater.on(
    "update-downloaded",
    (
      event,
      releaseNotes,
      releaseName,
      releaseDate,
      updateUrl,
      quitAndUpdate
    ) => {
      autoUpdater.quitAndInstall();
    }
  );
}

App.vue

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  第222版本
  <button @click="autoUpdate">获取更新</button>
</template>

<script setup>
import { onMounted } from "vue";

onMounted(() => {
  setTimeout(() => {
    window.electron.onMessage((val) => {
      console.log(val, "=====");
    });
  }, 1000);
});

function autoUpdate() {
  window.electron.ipcRenderer.send("update");
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

preload.js

import { contextBridge, ipcRenderer } from "electron";

contextBridge.exposeInMainWorld("electron", {
  ipcRenderer,
  onMessage: (fn) => {
    ipcRenderer.on("message", (event, ...args) => fn(...args));
  }
});

vue.config.js

module.exports = {
  pluginOptions: {
    electronBuilder: {
      preload: "src/preload.js",
      builderOptions: {
        publish: [
          {
            provider: "generic",
            url: "http:127.0.0.1:8080"
          }
        ]
      }
    }
  }
};

package.json

{
  "name": "electron_vue",
  "version": "0.0.2",
  "author": "352056038@qq.com",
  "description": "electron update test",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "start": "vue-cli-service electron:serve",
    "build": "vue-cli-service build",
    "electron:build": "vue-cli-service electron:build",
    "electron:serve": "vue-cli-service electron:serve",
    "postinstall": "electron-builder install-app-deps",
    "postuninstall": "electron-builder install-app-deps"
  },
  "main": "background.js",
  "dependencies": {
    "core-js": "^3.6.5",
    "electron-log": "^4.4.6",
    "register-service-worker": "^1.7.1",
    "vue": "^3.2.19"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-pwa": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.2.19",
    "electron": "^13.0.0",
    "electron-devtools-installer": "^3.1.0",
    "electron-updater": "^4.6.1",
    "vue-cli-plugin-electron-builder": "~2.1.1"
  },
}

注意

如果是vite可以在json中添加

  "publish": [
      {
        "provider": "generic",
        "url": "http:127.0.0.1:8080"
      }
    ]
 类似资料: