如何防止Electron中的多个示例

kupeojn6  于 2023-09-28  发布在  Electron
关注(0)|答案(4)|浏览(151)

我不知道这是否可能,但我不妨给予它一个机会,并要求。我正在做一个电子应用程序,我想知道是否有可能一次不超过一个示例。
我已经找到了这个gist,但我不确定热使用它。有没有人能给我一点启发,分享一个更好的想法?

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

lxkprmvk1#

现在有一个新的API:请求单示例锁

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

3phpmpom2#

app模块中使用makeSingleInstance函数,文档中甚至有一个示例。

w8f9ii69

w8f9ii693#

万一你需要密码。

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

n9vozmp44#

我只找到一种方法来工作电子16,makesingleinstance是弃用...使用这个:

const additionalData = { myKey: 'myValue' };
  const gotTheLock = app.requestSingleInstanceLock(additionalData);

      if (!gotTheLock) {
        app.quit();
      } else {
        app.on(
        'second-instance',
        (event, commandLine, workingDirectory, additionalData) => {
          // Print out data received from the second instance.
          console.log(additionalData);
          // Someone tried to run a second instance, we should focus our window.
          if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore();
            mainWindow.focus();
          }
        });
        app.whenReady().then(() => {
            createWindow();
        });
      }

相关问题