Electron实例代码

Electron 实例代码

以下是一些比较实用的Electron的代码。

为应用程序添加右键菜单

这段代码应该添加到 html 中的页面中

<script>
const { remote } = require('electron');
const { Menu, MenuItem } = remote;

const menu = new Menu();
menu.append(new MenuItem({ label: 'MenuItem1', click() { console.log('item 1 clicked') } }));
menu.append(new MenuItem({ type: 'separator' }));
menu.append(new MenuItem({ label: 'MenuItem2', type: 'checkbox', checked: true }));

window.addEventListener('contextmenu', (e) => {
  e.preventDefault();
  menu.popup({ window: remote.getCurrentWindow() });
}, false);
</script>

限制只能运行一个实例的代码

限制只能运行一个实例,需要用到 Electron 的 app.requestSingleInstanceLock()方法, 此方法的返回值表示我们的应用程序实例是否成功取得了锁。 如果它取得锁失败,则可以认为已经有一个实例获取了锁,并且正在运行,我们可以使用 app.quit() 方法立即结束当前实例的运行。 调用 app.requestSingleInstanceLock()方法,会触发前一个实例(如果存在前一个实例)的second-instance事件,我们可以在这个事件里面做点什么,例如激活前一个实例的窗口并获取焦点,示例代码如下

const { app } = require("electron");
let myWindow = null;
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
} else {
  app.on("second-instance", (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    if (myWindow) {
      if (myWindow.isMinimized()) {
        myWindow.restore();
      }
      myWindow.focus();
    }
  });

  // 创建 myWindow, 加载应用的其余部分, etc...
  app.on("ready", () => {});
}

创建菜单的代码

const template = [
  // { role: 'appMenu' }
  process.platform === "darwin"
    ? [
        {
          label: app.getName(),
          submenu: [
            { role: "about" },
            { type: "separator" },
            { role: "services" },
            { type: "separator" },
            { role: "hide" },
            { role: "hideothers" },
            { role: "unhide" },
            { type: "separator" },
            { role: "quit" },
          ],
        },
      ]
    : [],
  // { role: 'fileMenu' }
  {
    label: "File",
    submenu: [isMac ? { role: "close" } : { role: "quit" }],
  },
  // { role: 'editMenu' }
  {
    label: "Edit",
    submenu: [
      { role: "undo" },
      { role: "redo" },
      { type: "separator" },
      { role: "cut" },
      { role: "copy" },
      { role: "paste" },
      ...(isMac
        ? [
            { role: "pasteAndMatchStyle" },
            { role: "delete" },
            { role: "selectAll" },
            { type: "separator" },
            {
              label: "Speech",
              submenu: [{ role: "startspeaking" }, { role: "stopspeaking" }],
            },
          ]
        : [{ role: "delete" }, { type: "separator" }, { role: "selectAll" }]),
    ],
  },
  // { role: 'viewMenu' }
  {
    label: "View",
    submenu: [
      { role: "reload" },
      { role: "forcereload" },
      { role: "toggledevtools" },
      { type: "separator" },
      { role: "resetzoom" },
      { role: "zoomin" },
      { role: "zoomout" },
      { type: "separator" },
      { role: "togglefullscreen" },
    ],
  },
  // { role: 'windowMenu' }
  {
    label: "Window",
    submenu: [
      { role: "minimize" },
      { role: "zoom" },
      isMac
        ? [
            { type: "separator" },
            { role: "front" },
            { type: "separator" },
            { role: "window" },
          ]
        : [{ role: "close" }],
    ],
  },
  {
    role: "help",
    submenu: [
      {
        label: "Learn More",
        click: async () => {
          const { shell } = require("electron");
          await shell.openExternal("https://electronjs.org");
        },
      },
    ],
  },
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);

使用 Electron-updater 实现程序的检查更新

首先需要先按照electron-updater依赖,使用 npm install electron-updater --save。 然后在主线程的代码中可以使用如下的参考代码。

const { autoUpdater } = require("electron-updater");

let mainWindow;
const handleUpdate = () => {
  autoUpdater.setFeedURL("http://localhost/download/");

  autoUpdater.on("error", function (error) {
    console.log(error);
    mainWindow.webContents.send("check-update-error", error);
  });

  autoUpdater.on("checking-for-update", function () {
    console.log("检查更新了呢");
  });

  autoUpdater.on("update-available", function (info) {
    // 检查到新的版本的时候,会自动进行下载,下载完成后会触发update-downloaded事件。
    console.log("有新的版本");
    console.log(info);
    mainWindow.webContents.send("update-available");
  });

  autoUpdater.on("update-not-available", function (info) {
    console.log("当前没有新的版本");
    console.log(info);
    mainWindow.webContents.send("update-not-available");
  });

  autoUpdater.on("download-progress", function (progressObj) {
    console.log("下载进度更新了");
    console.log(progressObj);
  });

  autoUpdater.on(
    "update-downloaded",
    function (
      event,
      releaseNotes,
      releaseName,
      releaseDate,
      updateUrl,
      quitAndUpdate
    ) {
      ipcMain.on("doUpdateNow", (e, arg) => {
        console.log("关闭程序并更新");
        autoUpdater.quitAndInstall();
      });
      mainWindow.webContents.send("isUpdateNow");
    }
  );
};

主要是一些更新的时候,所用到的事件的处理,这个可以放在主窗口的创建的代码中调用。 然后检查更新的时候调用autoUpdater.checkForUpdates()

参考文献

[1] Electron 官方文档-中文版