Skip to main content

Command Palette

Search for a command to run...

How to get deep linking to work in Electron, on Windows

Published
2 min read
T

I'm a Front End Developer in Korea.

I work for a company called Lunit, that develops AI software to diagnose cancer.

From the UK, I came to Korea as an English teacher, and managed to retrain myself, and break out into the programming industry 😎

Part two to the deep linking adventure!

Part one, Linux, is here

To get this working on Windows, much of it is the same as Linux. There is only one thing that is different (well, two...)

In Windows, we don't need to add anything specific to the package.json file.

To get the app to go to the url on startup:

In main.js/index.ts

 if (process.platform !== "darwin") {
      console.log(
        `Start up with file: ${process.argv}`,
      );
      if (process.argv.length > 1) {
        mainWindow.webContents.send("send-share-link", {
          targetLink: process.argv[1].split("app-name://")[1],
        });
      }
    }

In the renderer file:

const { api } = window;

...

api.listenToDeepLink((data) => {
      if (data.targetLink) {
        history.push("/" + data.targetLink);
      }
    });

This is identical to Linux! Great, then we kill two birds with one stone.

Now, the difference:

const singleInstanceLock = app.requestSingleInstanceLock();

if (!singleInstanceLock) {
  app.quit();
} else {
  app.on("second-instance", (_, argv) => {
    console.log(`Instance lock triggered`);
    if (argv.length > 1) {
      // Only try this if there is an argv (might be redundant)
      if (process.platform == "win32" || process.platform === "linux") {
        try {
          console.log(
            `Direct link to file - SUCCESS: ${argv[1]}`,
          );
          mainWindow.webContents.send("send-share-link", {
            targetLink: argv[argv.length-1].split("app-name://")[1],
          });
        } catch {
          console.log(
            `Direct link to file - FAILED: ${argv}`,
          );
        }
      }
    }
  });
}

The difference is, when clicking the link when the app is already open, windows adds a whole stack of arguments into argv. The url is the last one, so we use argv[argv.length-1] to target that.

That should do it :)