Skip to main content

Deep Links深度链接

Overview概述

This guide will take you through the process of setting your Electron app as the default handler for a specific protocol.本指南将引导您完成将Electron应用程序设置为特定协议的默认处理程序的过程。

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. 在本教程结束时,我们将设置应用程序来拦截和处理任何以特定协议开始的点击URL。In this guide, the protocol we will use will be "electron-fiddle://".在本指南中,我们将使用的协议是“electron-fiddle://”。

Examples示例

Main Process主要过程 (main.js)

First, we will import the required modules from electron. 首先,我们将从electron导入所需的模块。These modules help control our application lifecycle and create a native browser window.这些模块有助于控制应用程序生命周期并创建本机浏览器窗口。

const { app, BrowserWindow, shell } = require('electron')
const path = require('path')

Next, we will proceed to register our application to handle all "electron-fiddle://" protocols.接下来,我们将继续注册应用程序以处理所有“electron-fiddle://”协议。

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

We will now define the function in charge of creating our browser window and load our application's index.html file.现在我们将定义负责创建浏览器窗口并加载应用程序的index.html文件的函数。

const createWindow = () => {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})

mainWindow.loadFile('index.html')
}

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.在下一步中,我们将创建BrowserWindow,并告诉应用程序如何处理单击外部协议的事件。

This code will be different in Windows compared to MacOS and Linux. 与MacOS和Linux相比,Windows中的代码将有所不同。This is due to Windows requiring additional code in order to open the contents of the protocol link within the same Electron instance. 这是因为Windows需要额外的代码才能打开同一Electron实例中协议链接的内容。Read more about this here.点击此处了解更多信息。

Windows code:

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
app.quit()
} else {
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()
}
})

// Create mainWindow, load the rest of the app, etc...
app.whenReady().then(() => {
createWindow()
})

// Handle the protocol. In this case, we choose to show an Error Box.
app.on('open-url', (event, url) => {
dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
})
}

MacOS and Linux code:

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
createWindow()
})

// Handle the protocol. In this case, we choose to show an Error Box.
app.on('open-url', (event, url) => {
dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
})

Finally, we will add some additional code to handle when someone closes our application.最后,我们将添加一些额外的代码,以便在有人关闭应用程序时处理。

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

Important notes重要提示

Packaging包装材料

On macOS and Linux, this feature will only work when your app is packaged. 在macOS和Linux上,此功能仅在打包应用程序时才起作用。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. 打包应用程序时,需要确保更新应用程序的macOS Info.plist和Linux.desktop文件,以包含新的协议处理程序。Some of the Electron tools for bundling and distributing apps handle this for you.一些捆绑和分发应用程序的Electron工具可以为您处理这一问题。

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):如果您使用的是Electron Forge,请在您的Forge配置中调整macOS支持的packagerConfig,以及相应的Linux makers for Linux支持的配置(请注意,以下示例仅显示添加配置更改所需的最低限度):

{
"config": {
"forge": {
"packagerConfig": {
"protocols": [
{
"name": "Electron Fiddle",
"schemes": ["electron-fiddle"]
}
]
},
"makers": [
{
"name": "@electron-forge/maker-deb",
"config": {
"mimeType": ["x-scheme-handler/electron-fiddle"]
}
}
]
}
}
}

Electron Packager

For macOS support:对于macOS支持:

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.如果您使用的是Electron Packager的API,则添加对protocols处理程序的支持与处理Electron Forge的方式类似,只是协议是传递给packager函数的打包选项的一部分。

const packager = require('electron-packager')

packager({
// ...other options...
protocols: [
{
name: 'Electron Fiddle',
schemes: ['electron-fiddle']
}
]

}).then(paths => console.log(`SUCCESS: Created ${paths.join(', ')}`))
.catch(err => console.error(`ERROR: ${err.message}`))

If you're using Electron Packager's CLI, use the --protocol and --protocol-name flags. 如果您使用的是Electron Packager的CLI,请使用--protocol--protocol-name标志。For example:例如:

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.启动Electron应用程序后,您可以在浏览器中输入包含自定义协议的URL,例如"electron-fiddle://open"并观察应用程序将响应并显示错误对话框。

// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell, dialog } = require('electron')
const path = require('path')

let mainWindow;

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

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
app.quit()
} else {
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()
}
})

// Create mainWindow, load the rest of the app, etc...
app.whenReady().then(() => {
createWindow()
})

app.on('open-url', (event, url) => {
dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
})
}

function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
}
})

mainWindow.loadFile('index.html')
}

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

// Handle window controls via IPC
ipcMain.on('shell:open', () => {
const pageDirectory = __dirname.replace('app.asar', 'app.asar.unpacked')
const pagePath = path.join('file://', pageDirectory, 'index.html')
shell.openExternal(pagePath)
})