windowselectronelectron-builder

How to get file path when opening it with electron app


I am making an app that has custom file extensions. I got the reading and writing of the file done and also the opening of the file on double-click on mac but i cannot find a way to make the double-tap give back the absolute path on windows. I am using electron-builder so all arguments that get passed are different

Here is how i solved it on MacOS:

main.js:

...
if (process.platform === "darwin") {
  app.on('open-file', (event, path) => {
    event.preventDefault();
    ipcMain.handle("getSource", function() {
      return path;
    })
  });
}

preload.js:

window.addEventListener('DOMContentLoaded', async () => {
...
let path;

    if (process.platform === "darwin") {

        const ipcRenderer = require('electron').ipcRenderer;

        path = await ipcRenderer.invoke("getSource")

    }
    if (process.platform === "win32") {
        path = process.argv[1]
    }

    gui_console.value = path
...
}

I tried with process.argv[1] as many of the other posts suggested and it gives me something else. in fact, process doesnt even contain the path of the file appearantly (I found this out by printing it to a textarea and copying the text into a json file). I saw a post with a solution that said require("electron").remote.process.argv[1] would work but after some time i realised this is the same thing.


Solution

  • The file path is indeed in process.argv, except you have to get it from the main process instead of the preload. I can't find any mentions in the docs that the value of args is different between processes, but in the open-file documentation it's mentioned that (emphasis mine):

    On Windows, you have to parse process.argv (in the main process) to get the filepath.

    Additionaly, if you don't want to rely on the argument's index to get the path and that you know the extension of the file you are looking for, you can use a find, for example:

    ipcMain.handle("getSource", () => {
      if (!app.isPackaged) return null;
      return process.argv.find(arg => arg.endsWith(".customExt"));
    });