title: Launching Your Electron App From a URL In Another App description: 本指南将会指导您配置 Electron 应用为特定协议的默认处理器。 slug: 从其他应用中的URL启动应用

hide_title: true

从其他应用中的 URL 启动您的应用

概览

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

通过此教程,您会掌握如何设置您的应用以拦截并处理任意特定协议的URL的点击事件。 在本指南中,我们假定这个协议名为“electron-fiddle://”。

示例

主进程(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')

其次,我们将应用注册为“electron-fiddle://”协议的处理器。

  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. }

现在我们定义负责创建浏览器窗口的函数,并加载应用的 index.html 文件。

  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. }

紧接着,我们将创建 BrowserWindow 并在应用中定义如何处理此外部协议被点击的事件。

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. 请点击 此处 了解更多

Windows 下代码:

  1. const gotTheLock = app.requestSingleInstanceLock()
  2. if (!gotTheLock) {
  3. app.quit()
  4. } else {
  5. app.on('second-instance', (event, commandLine, workingDirectory) => {
  6. // 用户正在尝试运行第二个实例,我们需要让焦点指向我们的窗口
  7. if (mainWindow) {
  8. if (mainWindow.isMinimized()) mainWindow.restore()
  9. mainWindow.focus()
  10. }
  11. })
  12. // 创建 mainWindow,加载其他资源,等等……
  13. app.whenReady().then(() => {
  14. createWindow()
  15. })
  16. // Handle the protocol. 在本例中,我们选择显示一个错误提示对话框。
  17. app.on('open-url', (event, url) => {
  18. dialog.showErrorBox('欢迎回来', `导向自: ${url}`)
  19. })
  20. }

MacOS 与 Linux 下代码:

  1. // Electron 在完成初始化,并准备创建浏览器窗口时,
  2. // 会调用这个方法。
  3. // 部分 API 在 ready 事件触发后才能使用。
  4. app.whenReady().then(() => {
  5. createWindow()
  6. })
  7. // Handle the protocol. 在本例中,我们选择显示一个错误提示对话框。
  8. app.on('open-url', (event, url) => {
  9. dialog.showErrorBox('欢迎回来', `导向自: ${url}`)
  10. })

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

  1. // 在除 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

打包

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"

结论

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.