2016-03-10 16 views
7

Ich weiß nicht, ob das möglich ist, aber ich könnte es auch eine Chance geben und fragen. Ich mache eine Electron-App und ich würde gerne wissen, ob es möglich ist, nicht mehr als eine einzige Instanz zu einer Zeit zu haben.Wie man mehrere Instanzen in Elektron verhindert

Ich habe dieses gist gefunden, aber ich bin nicht sicher heiß, es zu benutzen. Kann jemand eine bessere Idee teilen?

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

Antwort

13

Verwenden Sie die makeSingleInstance Funktion im app Modul, gibt es auch ein Beispiel in der Dokumentation.

+0

Wow, ich fühle mich dumm. Ich habe das nie in ihrer API gesehen. Ich habe von hier gelesen [http://electron.atom.io/docs/v0.36.8/](http://electron.atom.io/docs/v0.36.8/) – Eduard

0

Falls Sie den Code benötigen.

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