乐闻世界logo
搜索文章和话题

How to prevent multiple instances in Electron

1个答案

1

In Electron applications, it is essential to ensure that only a single instance runs. To prevent multiple instances from occurring, utilize the requestSingleInstanceLock method and second-instance event of the app module. Here are the steps to implement this:

  1. In the main process of the application, attempt to acquire the single-instance lock.

  2. If the lock cannot be acquired (indicating another instance is already running), the current instance should terminate immediately.

  3. If the lock is successfully acquired, listen for the second-instance event, which triggers when another instance is launched, allowing you to manipulate the existing instance, such as bringing the window to the foreground.

Here is an example of how to implement this logic:

javascript
const { app, BrowserWindow } = require('electron'); let mainWindow; function createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true } }); mainWindow.loadFile('index.html'); mainWindow.on('closed', () => { mainWindow = null; }); } // This method should be called only once during the module's lifecycle const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { // If the lock cannot be acquired (indicating another instance is already running), the current instance should terminate immediately. app.quit(); } else { // This event triggers when a second instance is launched app.on('second-instance', (event, commandLine, workingDirectory) => { // When a second instance is launched, bring the main window to the foreground if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.focus(); } }); // Electron is ready to create the browser window // Some APIs can only be used after this event app.on('ready', createWindow); } app.on('window-all-closed', () => { // On macOS, the application and menu bar remain active unless the user confirms exit with Cmd + Q if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate', () => { // On macOS, when clicking the dock icon and no other window is open, typically recreate a window in the application if (mainWindow === null) { createWindow(); } });

In the above code, we first attempt to acquire the single-instance lock using the requestSingleInstanceLock method. If it returns false, it indicates that another instance is already running, and we call app.quit() to terminate the program. If the lock is successfully acquired, we listen for the second-instance event, which triggers when another instance is launched, allowing us to manipulate the existing instance, such as bringing the window to the foreground.

This configuration ensures that your Electron application runs as a single instance, and when attempting to open a second instance, the focus is returned to the existing window.

2024年6月29日 12:07 回复

你的答案