2016-03-10 15 views
7

Non so se questo è possibile ma potrei anche dargli una possibilità e chiedere. Sto facendo un'app Electron e mi piacerebbe sapere se è possibile avere non più di una singola istanza alla volta.Come prevenire più istanze in Electron

Ho trovato questo gist ma non sono sicuro di usarlo. Qualcuno può far luce per condividere un'idea migliore?

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);; 
    }); 
} 

risposta

13

Utilizzare la funzione makeSingleInstance nel modulo app, c'è anche una lista nella documentazione.

+0

Wow, mi sento stupido. Non l'ho mai visto nella loro API. Stavo leggendo da qui [http://electron.atom.io/docs/v0.36.8/](http://electron.atom.io/docs/v0.36.8/) – Eduard

0

In caso sia necessario il codice.

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() 
}