如何在Electron中防止多个实例 [英] How to prevent multiple instances in Electron

查看:606
本文介绍了如何在Electron中防止多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 instance at a time.

I找到了这个要点,但我不确定使用它的热情。有人可以分享一些更好的主意吗?

I have found this gist but I'm not sure hot to use it. Can someone shed some light of share a better idea ?

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


推荐答案

现在有一个新的API : requestSingleInstanceLock

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

这篇关于如何在Electron中防止多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆