Stuart
Stuart

Reputation: 1

Enforce single instance of electron app on Windows, but make a launcher click open new window

I want to enforce a Single Instance for my electron app. When a user clicks the app shortcut icon on Windows, I want to enforce the single instance, but still open up a new window on the main instance when this happens.

All other current solutions seem to just quit the new instance and refocus the current instance.

  const singleInstanceLock = app.requestSingleInstanceLock();
  if (!singleInstanceLock) {

    app.exit();
  } else {
    app.focus();
  }

  app.on('second-instance', (_event: Electron.Event, argv: string[]) => {

     app.focus();
  
     // code to open up second window lives here. As far as I can tell, it doesnt get called
  });

Upvotes: 0

Views: 1418

Answers (1)

Joshua
Joshua

Reputation: 5322

app.exit(); Is a more severe way of quitting an app which quits all the instances of Electron instead of just the current one.

Try using app.quit() instead.

Also, separately, I'd re-arrange your code so it's like this:

const singleInstanceLock = app.requestSingleInstanceLock();
if (!singleInstanceLock) {

  app.quit();
} else {
  app.on('second-instance', (_event: Electron.Event, argv: string[]) => {

     app.focus();

     // Code to open up second window goes here.
  });
}

Replacing your first app.focus() with the app.on('second-instance'.

This is because you're running app.requestSingleInstanceLock() when the app first starts (as it should), but doing app.focus() wouldn't do anything since the app was only just opened, and there wouldn't be any windows to focus.

Upvotes: 0

Related Questions