如何防止Electron中的多个实例

Edu*_*ard 24 electron

我不知道这是否可能,但我不妨给它一个机会并问.我正在做一个Electron应用程序,我想知道是否有可能一次只有一个实例.

我找到了这个要点,但我不确定使用它.有人可以分享一些更好的想法吗?

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);;
    });
}
Run Code Online (Sandbox Code Playgroud)

r03*_*r03 40

现在有一个新的API: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', () => {
  })
}
Run Code Online (Sandbox Code Playgroud)

  • 请记住,app.quit() 不会立即终止,因此如果您之后有代码,它仍然会运行。 (3认同)
  • 这是需要的,因为电子 4.0 (2认同)

Vad*_*gon 30

使用模块中的makeSingleInstance功能,app甚至在文档中都有一个例子.

  • 此版本的版本低于electronic 4.0 (3认同)
  • Electron 4的发行说明说`makeSingleInstance` [已过时](https://github.com/electron/electron/blob/master/docs/api/breaking-changes.md#planned-breaking-api-changes-40 )。使用`requestSingleInstanceLock`。 (2认同)

man*_*mar 8

万一您需要代码。

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()
}
Run Code Online (Sandbox Code Playgroud)