How to keep only single instance of Electron App ?

When I recently working on Electron.JS project then I come across a strange problem. Actually to requirement there must be only one instance of the app. If someone try to click again on the launcher icon again on system then It must not run two instances of app rather it must refocus the window in currently running app instance.

So solve this problem I am going to share my code snippet which may be useful for you as well.

var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
  // Someone tried to run a second instance, we should focus our window.
  if (mainWindow) { 
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  }
});

if (shouldQuit) {
  app.quit();
}

This is the code which is doing the trick. It is checking if any instance is available then refocus it otherwise just create a new instance and run it.

You may my full file where I implemented in the project.

https://gist.github.com/CodeNextGen/af99bc7aaf71ff8dd795b7ff5e6804cf

I hope you are going to like this.Thanks for being here.


Tagged with:
CodeNextGen
Written by Sanjeev Kumar

Get notifications about new posts on Twitter, RSS or Email.