【发布时间】:2021-02-05 10:36:55
【问题描述】:
我需要从浏览器链接启动电子应用程序或将其聚焦(如果已启动)。我已经搜索并尝试了许多解决方案,但没有让它发挥作用,所以如果有人对此有任何经验,你能帮忙吗?
代码如下:
// Single instance app ==========
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 (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
// Register private URI scheme for the current user when running for the first time
app.setAsDefaultProtocolClient('x-protocol');
当我尝试使用此代码启动时,我得到 goTheLock 值为 false,但 second-instance 事件没有被触发,不知道为什么。
版本详情:
平台:Windows 10
电子:8.5.3
电子制造商: 21.2.0
更新:
我在退出 !gotTheLock 内的应用程序之前添加了 5 秒的延迟,在这种情况下,我收到了事件。
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
delay(5000); // 5 seconds delay
app.quit();
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// Someone tried to run a second instance, we should focus our window.
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
}
【问题讨论】: