Launching Your Electron App From A URL In Another App

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

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 compared to MacOS and Linux. This is due to 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 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. })
  12. // Create mainWindow, load the rest of the app, etc...
  13. app.whenReady().then(() => {
  14. createWindow()
  15. })
  16. // Handle the protocol. In this case, we choose to show an Error Box.
  17. app.on('open-url', (event, url) => {
  18. dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
  19. })
  20. }

MacOS and Linux 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.

  • index.html
  • main.js
  • preload.js
  • renderer.js
  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/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. // Modules to control application life and create native browser window
  2. const { app, BrowserWindow, ipcMain, shell, dialog } = require('electron')
  3. const path = require('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. })
  23. // Create mainWindow, load the rest of the app, etc...
  24. app.whenReady().then(() => {
  25. createWindow()
  26. })
  27. app.on('open-url', (event, url) => {
  28. dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
  29. })
  30. }
  31. function createWindow () {
  32. // Create the browser window.
  33. mainWindow = new BrowserWindow({
  34. width: 800,
  35. height: 600,
  36. webPreferences: {
  37. preload: path.join(__dirname, 'preload.js'),
  38. }
  39. })
  40. mainWindow.loadFile('index.html')
  41. }
  42. // Quit when all windows are closed, except on macOS. There, it's common
  43. // for applications and their menu bar to stay active until the user quits
  44. // explicitly with Cmd + Q.
  45. app.on('window-all-closed', function () {
  46. if (process.platform !== 'darwin') app.quit()
  47. })
  48. // Handle window controls via IPC
  49. ipcMain.on('shell:open', () => {
  50. const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked')
  51. const pagePath = path.join('file://', pageDirectory, 'index.html')
  52. shell.openExternal(pagePath)
  53. })
  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. // 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. shell.open();
  7. });

Open in Fiddle