How to prevent multiple instances in Electron

后端 未结 3 883
一整个雨季
一整个雨季 2021-02-01 13:08

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

相关标签:
3条回答
  • 2021-02-01 13:48

    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', () => {
      })
    }
    
    0 讨论(0)
  • 2021-02-01 14:00

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

    0 讨论(0)
  • 2021-02-01 14:11

    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()
    }
    
    0 讨论(0)
提交回复
热议问题