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

Gre*_* R. 5 javascript electron

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();
});
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*ook 5

更新:文档中的示例看起来是最好的模式!即返回 falseapp.quit()时调用app.requestSingleInstanceLock()


文档

当第二个实例被执行并调用 app.requestSingleInstanceLock() 时,此事件将在应用程序的实例内发出。

即这就是app.quit()关闭第一个窗口的原因。

... 通常应用程序通过使它们的主窗口聚焦和非最小化来对此做出响应。

因此,如果您的主进程win的实例是BrowserWindow打开的,您可以执行以下操作:

win.show()
win.focus()
Run Code Online (Sandbox Code Playgroud)

我相信您也可以在“第二个实例”处理程序中什么都不做:该事件仅用于提供信息,告诉您用户已尝试第二次打开您的应用程序。