1

I'm using electron 2.0.7 and I want to prevent multiple instances of the app by using app.makeSingleInstance.

It works but when i'm trying to run another instance of the app I get this error: "A Javascript error is occurred in the main process" as a pop up.

This is the code in main.ts:

function checkSingleInstance() {
  // to make singleton instance
  const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (win) {
      if (win.isMinimized()) {
        win.restore();
        win.focus();
      }
    }
  });

  if (isSecondInstance) {
    app.quit();
    return;
  }
}

checkSingleInstance();

This is the error:

A Javascript error is occurred in the main process

Community
  • 1
  • 1
Umberto
  • 164
  • 1
  • 13

2 Answers2

1

Try replacing app.quit() with app.exit().

app.exit() does not emit events before quitting as opposed to app.quit() which does the proper cleanup.

It's hard to say exactly where the error is coming from and why, but this issue is documented here.

pushkin
  • 9,575
  • 15
  • 51
  • 95
0

After completing the source code you posted, I can run it using Electron 2.0.7 just fine.

The error you're seeing probably stems from some other part of your code. Judging by the error message, check if you import a module by the name screen somewhere.


Here's your source code, completed to a MCVE:

const {app, BrowserWindow} = require('electron')

let win = null

console.log(`Node ${process.versions.node}, Chrome ${process.versions.chrome}, Electron ${process.versions.electron}`)

function checkSingleInstance() {
  // to make singleton instance
  const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (win) {
      if (win.isMinimized()) {
        win.restore();
        win.focus();
      }
    }
  });

  if (isSecondInstance) {
    console.log("Exiting because another instance is running")
    app.quit();
    return;
  }
}

checkSingleInstance();

app.on('ready', () => {
  win = new BrowserWindow({width: 200, height: 200});
  win.on('closed', () => win = null);
});
snwflk
  • 3,341
  • 4
  • 25
  • 37
  • Hi, here the full code: https://github.com/ulver2812/aws-s3-backup/blob/milestone-1.5.0/main.ts I don't posted it here because it's long. Thanks – Umberto Mar 11 '19 at 08:00
  • Please make a new minimal code example that only demonstrates your issue (https://stackoverflow.com/help/mcve). This is part of the effort expected from users before posting a question. – snwflk Mar 11 '19 at 13:30
  • 1
    makeSingleInstance is deprecated. Please see https://stackoverflow.com/questions/56161168/typeerror-app-makesingleinstance-is-not-a-function – Dika May 04 '22 at 03:31