Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent multiple instances in Electron

Tags:

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);;
    });
}
like image 361
Eduard Avatar asked Mar 10 '16 12:03

Eduard


3 Answers

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', () => {
  })
}

like image 94
roeland Avatar answered Oct 11 '22 20:10

roeland


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

like image 22
Vadim Macagon Avatar answered Oct 11 '22 19:10

Vadim Macagon


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()
}
like image 9
manish kumar Avatar answered Oct 11 '22 19:10

manish kumar