From 35e5e782aca29aa715c93eba80af072a26f6bc05 Mon Sep 17 00:00:00 2001 From: Matthew Gordon Date: Thu, 26 Sep 2019 14:56:23 +0100 Subject: [PATCH] Added option to only allow a single instance of the Electron app. If a second instance is opened, it closes immediately and the original instance receives focus. Signed-off-by: Matthew Gordon --- .../src/generator/frontend-generator.ts | 20 +++++++++++++++++++ .../src/application-props.ts | 5 +++++ 2 files changed, 25 insertions(+) diff --git a/dev-packages/application-manager/src/generator/frontend-generator.ts b/dev-packages/application-manager/src/generator/frontend-generator.ts index ee4835da19d70..eb22ca69c152d 100644 --- a/dev-packages/application-manager/src/generator/frontend-generator.ts +++ b/dev-packages/application-manager/src/generator/frontend-generator.ts @@ -128,6 +128,13 @@ const { fork } = require('child_process'); const { app, shell, BrowserWindow, ipcMain, Menu } = electron; const applicationName = \`${this.pck.props.frontend.config.applicationName}\`; +const isSingleInstance = ${this.pck.props.backend.config.singleInstance === true ? 'true' : 'false'}; + +if (isSingleInstance && !app.requestSingleInstanceLock()) { + // There is another instance running, exit now. The other instance will request focus. + app.quit(); + return; +} const nativeKeymap = require('native-keymap'); const Storage = require('electron-store'); @@ -285,6 +292,19 @@ app.on('ready', () => { // @ts-ignore const devMode = process.defaultApp || /node_modules[\/]electron[\/]/.test(process.execPath); const mainWindow = createNewWindow(); + + if (isSingleInstance) { + app.on('second-instance', (event, commandLine, workingDirectory) => { + // Someone tried to run a second instance, we should focus our window. + if (mainWindow && !mainWindow.isDestroyed()) { + if (mainWindow.isMinimized()) { + mainWindow.restore(); + } + mainWindow.focus() + } + }) + } + const loadMainWindow = (port) => { if (!mainWindow.isDestroyed()) { mainWindow.loadURL('file://' + join(__dirname, '../../lib/index.html') + '?port=' + port); diff --git a/dev-packages/application-package/src/application-props.ts b/dev-packages/application-package/src/application-props.ts index 810dae2912b85..cb1770d59d69b 100644 --- a/dev-packages/application-package/src/application-props.ts +++ b/dev-packages/application-package/src/application-props.ts @@ -116,6 +116,11 @@ export interface FrontendApplicationConfig extends ApplicationConfig { */ export interface BackendApplicationConfig extends ApplicationConfig { + /** + * If true and in Electron mode, only one instance of the application is allowed to run at a time. + */ + singleInstance?: boolean; + } /**