Deep Links

Overview

This guide will take you through the process of setting your Electron app as the default handler for a specific protocol.

By the end of this tutorial, we will have set our app to intercept and handle any clicked URLs that start with a specific protocol. In this guide, the protocol we will use will be “electron-fiddle://“.

Examples

Main Process (main.js)

First, we will import the required modules from electron. These modules help control our application lifecycle and create a native browser window.

  1. const { app, BrowserWindow, shell } = require('electron')
  2. const path = require('node:path')

Next, we will proceed to register our application to handle all “electron-fiddle://“ protocols.

  1. if (process.defaultApp) {
  2. if (process.argv.length >= 2) {
  3. app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])])
  4. }
  5. } else {
  6. app.setAsDefaultProtocolClient('electron-fiddle')
  7. }

We will now define the function in charge of creating our browser window and load our application’s index.html file.

  1. let mainWindow
  2. const createWindow = () => {
  3. // Create the browser window.
  4. mainWindow = new BrowserWindow({
  5. width: 800,
  6. height: 600,
  7. webPreferences: {
  8. preload: path.join(__dirname, 'preload.js')
  9. }
  10. })
  11. mainWindow.loadFile('index.html')
  12. }

In this next step, we will create our BrowserWindow and tell our application how to handle an event in which an external protocol is clicked.

This code will be different in Windows and Linux compared to MacOS. This is due to both platforms emitting the second-instance event rather than the open-url event and Windows requiring additional code in order to open the contents of the protocol link within the same Electron instance. Read more about this here.

Windows and Linux code:

  1. const gotTheLock = app.requestSingleInstanceLock()
  2. if (!gotTheLock) {
  3. app.quit()
  4. } else {
  5. app.on('second-instance', (event, commandLine, workingDirectory) => {
  6. // Someone tried to run a second instance, we should focus our window.
  7. if (mainWindow) {
  8. if (mainWindow.isMinimized()) mainWindow.restore()
  9. mainWindow.focus()
  10. }
  11. // the commandLine is array of strings in which last element is deep link url
  12. dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop()}`)
  13. })
  14. // Create mainWindow, load the rest of the app, etc...
  15. app.whenReady().then(() => {
  16. createWindow()
  17. })
  18. }

MacOS code:

  1. // This method will be called when Electron has finished
  2. // initialization and is ready to create browser windows.
  3. // Some APIs can only be used after this event occurs.
  4. app.whenReady().then(() => {
  5. createWindow()
  6. })
  7. // Handle the protocol. In this case, we choose to show an Error Box.
  8. app.on('open-url', (event, url) => {
  9. dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
  10. })

Finally, we will add some additional code to handle when someone closes our application.

  1. // Quit when all windows are closed, except on macOS. There, it's common
  2. // for applications and their menu bar to stay active until the user quits
  3. // explicitly with Cmd + Q.
  4. app.on('window-all-closed', () => {
  5. if (process.platform !== 'darwin') app.quit()
  6. })

Important notes

Packaging

On macOS and Linux, this feature will only work when your app is packaged. It will not work when you’re launching it in development from the command-line. When you package your app you’ll need to make sure the macOS Info.plist and the Linux .desktop files for the app are updated to include the new protocol handler. Some of the Electron tools for bundling and distributing apps handle this for you.

Electron Forge

If you’re using Electron Forge, adjust packagerConfig for macOS support, and the configuration for the appropriate Linux makers for Linux support, in your Forge configuration (please note the following example only shows the bare minimum needed to add the configuration changes):

  1. {
  2. "config": {
  3. "forge": {
  4. "packagerConfig": {
  5. "protocols": [
  6. {
  7. "name": "Electron Fiddle",
  8. "schemes": ["electron-fiddle"]
  9. }
  10. ]
  11. },
  12. "makers": [
  13. {
  14. "name": "@electron-forge/maker-deb",
  15. "config": {
  16. "mimeType": ["x-scheme-handler/electron-fiddle"]
  17. }
  18. }
  19. ]
  20. }
  21. }
  22. }

Electron Packager

For macOS support:

If you’re using Electron Packager’s API, adding support for protocol handlers is similar to how Electron Forge is handled, except protocols is part of the Packager options passed to the packager function.

  1. const packager = require('electron-packager')
  2. packager({
  3. // ...other options...
  4. protocols: [
  5. {
  6. name: 'Electron Fiddle',
  7. schemes: ['electron-fiddle']
  8. }
  9. ]
  10. }).then(paths => console.log(`SUCCESS: Created ${paths.join(', ')}`))
  11. .catch(err => console.error(`ERROR: ${err.message}`))

If you’re using Electron Packager’s CLI, use the --protocol and --protocol-name flags. For example:

  1. npx electron-packager . --protocol=electron-fiddle --protocol-name="Electron Fiddle"

Conclusion

After you start your Electron app, you can enter in a URL in your browser that contains the custom protocol, for example "electron-fiddle://open" and observe that the application will respond and show an error dialog box.

docs/fiddles/system/protocol-handler/launch-app-from-URL-in-another-app (27.0.1)Open in Fiddle

  • main.js
  • preload.js
  • index.html
  • renderer.js
  1. // Modules to control application life and create native browser window
  2. const { app, BrowserWindow, ipcMain, shell, dialog } = require('electron')
  3. const path = require('node:path')
  4. let mainWindow
  5. if (process.defaultApp) {
  6. if (process.argv.length >= 2) {
  7. app.setAsDefaultProtocolClient('electron-fiddle', process.execPath, [path.resolve(process.argv[1])])
  8. }
  9. } else {
  10. app.setAsDefaultProtocolClient('electron-fiddle')
  11. }
  12. const gotTheLock = app.requestSingleInstanceLock()
  13. if (!gotTheLock) {
  14. app.quit()
  15. } else {
  16. app.on('second-instance', (event, commandLine, workingDirectory) => {
  17. // Someone tried to run a second instance, we should focus our window.
  18. if (mainWindow) {
  19. if (mainWindow.isMinimized()) mainWindow.restore()
  20. mainWindow.focus()
  21. }
  22. dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop().slice(0, -1)}`)
  23. })
  24. // Create mainWindow, load the rest of the app, etc...
  25. app.whenReady().then(() => {
  26. createWindow()
  27. })
  28. app.on('open-url', (event, url) => {
  29. dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
  30. })
  31. }
  32. function createWindow () {
  33. // Create the browser window.
  34. mainWindow = new BrowserWindow({
  35. width: 800,
  36. height: 600,
  37. webPreferences: {
  38. preload: path.join(__dirname, 'preload.js')
  39. }
  40. })
  41. mainWindow.loadFile('index.html')
  42. }
  43. // Quit when all windows are closed, except on macOS. There, it's common
  44. // for applications and their menu bar to stay active until the user quits
  45. // explicitly with Cmd + Q.
  46. app.on('window-all-closed', function () {
  47. if (process.platform !== 'darwin') app.quit()
  48. })
  49. // Handle window controls via IPC
  50. ipcMain.on('shell:open', () => {
  51. const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked')
  52. const pagePath = path.join('file://', pageDirectory, 'index.html')
  53. shell.openExternal(pagePath)
  54. })
  1. // All of the Node.js APIs are available in the preload process.
  2. // It has the same sandbox as a Chrome extension.
  3. const { contextBridge, ipcRenderer } = require('electron')
  4. // Set up context bridge between the renderer process and the main process
  5. contextBridge.exposeInMainWorld(
  6. 'shell',
  7. {
  8. open: () => ipcRenderer.send('shell:open')
  9. }
  10. )
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
  6. <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
  7. <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
  8. <title>app.setAsDefaultProtocol Demo</title>
  9. </head>
  10. <body>
  11. <h1>App Default Protocol Demo</h1>
  12. <p>The protocol API allows us to register a custom protocol and intercept existing protocol requests.</p>
  13. <p>These methods allow you to set and unset the protocols your app should be the default app for. Similar to when a
  14. browser asks to be your default for viewing web pages.</p>
  15. <p>Open the <a href="https://www.electronjs.org/docs/latest/api/protocol">full protocol API documentation</a> in your
  16. browser.</p>
  17. -----
  18. <h3>Demo</h3>
  19. <p>
  20. First: Launch current page in browser
  21. <button id="open-in-browser" class="js-container-target demo-toggle-button">
  22. Click to Launch Browser
  23. </button>
  24. </p>
  25. <p>
  26. Then: Launch the app from a web link!
  27. <a href="electron-fiddle://open">Click here to launch the app</a>
  28. </p>
  29. ----
  30. <p>You can set your app as the default app to open for a specific protocol. For instance, in this demo we set this app
  31. as the default for <code>electron-fiddle://</code>. The demo button above will launch a page in your default
  32. browser with a link. Click that link and it will re-launch this app.</p>
  33. <h3>Packaging</h3>
  34. <p>This feature will only work on macOS when your app is packaged. It will not work when you're launching it in
  35. development from the command-line. When you package your app you'll need to make sure the macOS <code>plist</code>
  36. for the app is updated to include the new protocol handler. If you're using <code>electron-packager</code> then you
  37. can add the flag <code>--extend-info</code> with a path to the <code>plist</code> you've created. The one for this
  38. app is below:</p>
  39. <p>
  40. <h5>macOS plist</h5>
  41. <pre><code>
  42. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  43. &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt;
  44. &lt;plist version="1.0"&gt;
  45. &lt;dict&gt;
  46. &lt;key&gt;CFBundleURLTypes&lt;/key&gt;
  47. &lt;array&gt;
  48. &lt;dict&gt;
  49. &lt;key&gt;CFBundleURLSchemes&lt;/key&gt;
  50. &lt;array&gt;
  51. &lt;string&gt;electron-api-demos&lt;/string&gt;
  52. &lt;/array&gt;
  53. &lt;key&gt;CFBundleURLName&lt;/key&gt;
  54. &lt;string&gt;Electron API Demos Protocol&lt;/string&gt;
  55. &lt;/dict&gt;
  56. &lt;/array&gt;
  57. &lt;key&gt;ElectronTeamID&lt;/key&gt;
  58. &lt;string&gt;VEKTX9H2N7&lt;/string&gt;
  59. &lt;/dict&gt;
  60. &lt;/plist&gt;
  61. </code>
  62. </pre>
  63. <p>
  64. <!-- You can also require other files to run in this process -->
  65. <script src="./renderer.js"></script>
  66. </body>
  67. </html>
  1. // This file is required by the index.html file and will
  2. // be executed in the renderer process for that window.
  3. // All APIs exposed by the context bridge are available here.
  4. // Binds the buttons to the context bridge API.
  5. document.getElementById('open-in-browser').addEventListener('click', () => {
  6. window.shell.open()
  7. })