Skip to main content

URL protocol handler

It's fairly common to find web pages link to resources using non-http protocols. An example is the mailto: protocol:

<a href="mailto:webmaster@example.com">Web Master</a>

You might want your application to become the handler for a particular protocol well-known protocol (if you are an email application, for example) or even create your own custom protocol to handle links that navigate to particular places or states in your application. This is particularly useful when sharing some content with contacts and a common scenario many applications need to implement.

Implementation

To register a custom protocol in your Electron application you can use the setAsDefaultProtocolClient method of the app module.

const { app } = require('electron');

app.whenReady().then(() => {
app.setAsDefaultProtocolClient('mycustomprotocol');
});

Once registered, your application will be opened anytime a user interacts with a link similar to mycustomprotocol://custom/path. How the application access the URI is different depending on the platform.

For macOS is via the open-url event

const { app } = require('electron');

app.on('open-url', (event, url) => {
// Your code handling here
});

On Windows the URI is passed as part of the arguments (process.argv) when starting the application. Because the position could change, it is recommended to iterate to find the right one. An optimistic implementation would be:

const protocolArg = process.argv.find((arg) => arg.startsWith('mycustomprotocol://'));
if(!protocolArg){
return;
}

// Your code handling here
caution

Depending on the platform there might be some extra steps to do (like add the protocol to the app's info.plist on macOS). Make sure to read the official documentation.

Contrary to the PWA case, there are no limitations on the name of the protocol, thus why the name is mycustomprotocol and not web+mycustomprotocol.

If you have Fiddle installed, you can run a full example by clicking the following button:

Open in Fiddle