How to prevent multiple instances in Electron

I do not know if this is possible but I might as well give it a chance and ask. I'm doing an Electron app and I'd like to know if it is possible to have no more than a single instance at a time.

I have found this gist but I'm not sure hot to use it. Can someone shed some light of share a better idea ?

var preventMultipleInstances = function(window) {
    var socket = (process.platform === 'win32') ? '\\\\.\\pipe\\myapp-sock' : path.join(os.tmpdir(), 'myapp.sock');
    net.connect({path: socket}, function () {
        var errorMessage = 'Another instance of ' + pjson.productName + ' is already running. Only one instance of the app can be open at a time.'
        dialog.showMessageBox(window, {'type': 'error', message: errorMessage, buttons: ['OK']}, function() {
            window.destroy()
        })
    }).on('error', function (err) {
        if (process.platform !== 'win32') {
            // try to unlink older socket if it exists, if it doesn't,
            // ignore ENOENT errors
            try {
                fs.unlinkSync(socket);
            } catch (e) {
                if (e.code !== 'ENOENT') {
                    throw e;
                }
            }
        }
        net.createServer(function (connection) {}).listen(socket);;
    });
}

Solution 1:

There is a new API now: requestSingleInstanceLock

const { app } = require('electron')
let myWindow = null
    
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 (myWindow) {
      if (myWindow.isMinimized()) myWindow.restore()
      myWindow.focus()
    }
  })
    
  // Create myWindow, load the rest of the app, etc...
  app.on('ready', () => {
  })
}

Solution 2:

Use the makeSingleInstance function in the app module, there's even an example in the docs.

Solution 3:

In Case you need the code.

let mainWindow = null;
//to make singleton instance
const isSecondInstance = app.makeSingleInstance((commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        mainWindow.focus()
    }
})

if (isSecondInstance) {
    app.quit()
}