Skip to main content

How to open electron app via URLs or browser redirect




Overview

The goal of this tutorial is to show you how to open URLs or browser redirects in our electron app 

Introduction

In this process, we create a custom protocol and set our electron app as the handler for that custom protocol. This process is also known as deep linking process.

At the end of this tutorial your app-specific url will look something like this:
  your-protocol://path/page?data=value  

Prerequisites

  • Basic Electron project setup

Let's Get Started

First Step, register a custom protocol via the electron app using the code below. Try to keep the protocol not too generic so that it should not interfere with other app's deep link URLs.

const {app} = require('electron')
if (process.platform === "win32") {
  app.setAsDefaultProtocolClient("govdrive", process.execPath, [
    path.resolve(process.argv[1]),
  ]);
} else {
  app.setAsDefaultProtocolClient("govdrive");
}

Now our app is registered to handle our custom protocol. let's handle requests coming from URL. This code is different in Windows compared to MacOS and Linux because Windows require additional code in order to open the protocol link within the same Electron instance.

Windows :

// acquire the single instance lock for our application. This will prevent electron from opening second instance.
const gotTheLock = app.requestSingleInstanceLock()

//checking if we got the lock or not
if (!gotTheLock) {
  app.quit()
} else {

// the second-instance event handles the process to run when electron tries to open a second instance of our app.
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // Someone tried to run a second instance, we should focus our window.
    if (mainWindow) {
      if (mainWindow.isMinimized()) mainWindow.restore()
      mainWindow.focus()
    }
  })

  // Handling the protocol.
  app.on('open-url', (event, url) => {
    console.log('deep link url >',url)
  })
}

MacOs and Linux:


app.on('open-url', function (event, url) {
  event.preventDefault()
  deeplinkingUrl = url
  console.log("my-url > " + deeplinkingUrl)
})

Conclusion

Now After you start your Electron app, you can enter a URL in your browser that contains the custom protocol, for example "your-protocol://path/page?data=value" and observe that the application will respond and console the url in CLI.

Comments

Post a Comment