Skip to content

Commit

Permalink
Added option to only allow a single instance of the Electron app.
Browse files Browse the repository at this point in the history
If a second instance is opened, it closes immediately and the original
instance receives focus.

Signed-off-by: Matthew Gordon <matthew.gordon@arm.com>
  • Loading branch information
mcgordonite authored and thegecko committed Oct 4, 2019
1 parent 4a07198 commit 35e5e78
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions dev-packages/application-package/src/application-props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

}

/**
Expand Down

0 comments on commit 35e5e78

Please sign in to comment.