The best alternative that I have found for this problem is using second-instance event on the app module with process.argv.
When a user clicks a file associated with your app, on Windows (yeah! I only tried it on Windows), it will try to open a new instance of the app with the path of the related file inside process.argv. If you are not using multiple instances of the app, then you should prevent the app from opening multiple instances of the app and try to fetch the data (mainly the process.argv) to the main instance using the second-instance event from the app module.
First, you should get the singleInstanceLock from app.requestSingleInstanceLock() to make the current instance the only instance of the app. This will return a boolean. If it returns false, this means that another instance has the singleInstanceLock. Then you should close that instance using app.quit().
// Behaviour on second instance for parent process
const gotSingleInstanceLock = app.requestSingleInstanceLock();
if (!gotSingleInstanceLock) app.quit(); // Quits the app if app.requestSingleInstanceLock() returns false.
If the boolean is true, then this means the current app session is the main session of the app.
Then we should use the second-instance event of the app module to detect second instances from that point onwards. If another instance emerges, it will be closed, but second-instance event will be fired with the relevant arguments needed to identify what opened that instance to the process.argv. The second parameter of the callback added to the second-instance event can be used to get those arguments sent to that instance. From that point onwards, you can filter the strings inside the process.argv and get the relevant path of the file that opened the other instance.
// Behaviour on the second instance for the parent process
const gotSingleInstanceLock = app.requestSingleInstanceLock();
if (!gotSingleInstanceLock) app.quit();
else {
app.on('second-instance', (_, argv) => {
//User requested a second instance of the app.
//argv has the process.argv arguments of the second instance.
if (app.hasSingleInstanceLock()) {
if (mainWindow?.isMinimized()) mainWindow?.restore();
mainWindow?.focus();
process.argv = argv; // I tried to add the argv from the second instance to my main instance.
}
});
}
Please keep in mind that arguments in process.argv will be added differently when the app is packaged. Therefore, you should loop through the arguments and check whether an argument is a path in the system using the stat() function in the fs module and if it has the .txt extension at the end using the path.extname()
I found this method the hard way, so I hope that anyone with this problem wouldn't have to go through all of that.