control Electron instances

Viewed 167

Wanted to check how many instances are running and control the number of instances running in one exe electron bundle. Let us say I wanted to allow only three instances running for the one exe bundle. I am not able to do this.

Current Behavior:

Only one and remaining can block. Or open for any number of instances. We need to control only three instances running, not more than that.

Example:

const { app } = require('electron')
let myWindow = null
    
const gotTheLock = app.requestSingleInstanceLock()
    
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore()
      myWindow.focus()
    }
  })
    
  // Create myWindow, load the rest of the app, etc...
  app.on('ready', () => {
  })
}
2 Answers

You can try with the following code to know how many windows have been opened.

const count = BrowserWindow.getAllWindows().length;

To check visible windows, you can try the following code

let count = BrowserWindow.getAllWindows()
  .filter(b => {
    return b.isVisible()
  }).length

Once you get the number of instances, based upon the condition for number of instance, ie. if it is more than 3, you can quit using app.quit().

You can make each instance write to a file (increment a counter for example) when the instance starts and when it exits. (decrement the counter). You should check that file to see if the maximum number of instances are running

import { app } from "electron";
import path from "path";
import fs from "fs";

const MAX_APP_INSTANCES = 3;
const INSTANCE_COUNT_FILE_PATH = path.join(
  app.getPath("userData"),
  "numOfInstances"
);

// utils to read/write number of instances to a file
const instanceCountFileExists = () => fs.existsSync(INSTANCE_COUNT_FILE_PATH);
const readInstanceCountFile = () =>
  parseInt(fs.readFileSync(INSTANCE_COUNT_FILE_PATH, "utf-8"));
const writeInstanceCountFile = (value) =>
  fs.writeFileSync(INSTANCE_COUNT_FILE_PATH, value);
const incInstanceCountFile = () => {
  const value = readInstanceCountFile() + 1;
  writeInstanceCountFile(value.toString());
};
const decInstanceCountFile = () => {
  const value = readInstanceCountFile() - 1;
  writeInstanceCountFile(value.toString());
};

// logic needed to only allow a certain number of instances to be active
if (instanceCountFileExists() && readInstanceCountFile() >= MAX_APP_INSTANCES) {
  app.quit();
} else {
  if (!instanceCountFileExists()) {
    writeInstanceCountFile("1");
  } else {
    incInstanceCountFile();
  }
  app.on("quit", () => decInstanceCountFile());
}

Note: this is solution is somewhat hacky. For example, the quit event is not guaranteed to fire when the Electron app exits

Related