Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you force an electron app to have a single instance?

I'm trying to keep my electron app from being able to start more than one window at a time. I've already tried this, but it makes the first window opened close itself instead of the second window opened, and it completely stops working for the third window:

app.requestSingleInstanceLock();
app.on('second-instance', () => {
    app.quit();
});

The older app.makeSingleInstance also throws an error since it's deprecated. What should I do instead?

like image 465
Greyson R. Avatar asked Jan 28 '20 04:01

Greyson R.


1 Answers

Update: the example in the docs looks like the best pattern to follow! I.e. call app.quit() when app.requestSingleInstanceLock() returns false


From the docs:

This event will be emitted inside the primary instance of your application when a second instance has been executed and calls app.requestSingleInstanceLock().

I.e. this is why app.quit() shuts the first window.

... Usually applications respond to this by making their primary window focused and non-minimized.

So if win is the instance of BrowserWindow that your main process opened, you could do:

win.show()
win.focus()

I believe you could also do nothing in the 'second-instance' handler: the event is just for information, telling you that the user has tried to open your app a second time.

like image 81
Darren Cook Avatar answered Oct 16 '22 20:10

Darren Cook