跳到主要内容

深层链接

概述

本指南将引导您完成将 Electron 应用设置为特定协议默认处理程序的过程。

在本教程结束时,我们将把应用设置为拦截和处理任何以特定协议开头的点击式 URL。 在本指南中,我们将使用的协议是“electron-fiddle://”。

示例

主进程 (main.js)

首先,我们将从 electron 导入所需的模块。 这些模块有助于控制我们的应用生命周期并创建原生浏览器窗口。

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

接下来,我们将继续注册我们的应用程序来处理所有的“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')
}

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

let mainWindow

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

mainWindow.loadFile('index.html')
}

在下一步中,我们将创建我们的 BrowserWindow 并告知我们的应用程序如何处理点击外部协议的事件。

与 MacOS 相比,Windows 和 Linux 上的此代码将有所不同。 这是由于这两个平台都发射 second-instance 事件而非 open-url 事件,且 Windows 需要额外的代码才能在同一 Electron 实例中打开协议链接的内容。 在此阅读更多内容。

Windows 和 Linux 代码:

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()
}
// the commandLine is array of strings in which last element is deep link url
dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop()}`)
})

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

MacOS 代码:

// 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}`)
})

最后,我们将添加一些额外的代码来处理有人关闭我们的应用程序的情况。

// 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()
})

重要提示

打包

在 macOS 和 Linux 上,此功能仅在您的应用打包后才能工作。 在开发环境中从命令行启动它将不起作用。 打包应用时,需要确保 macOS Info.plist 和 Linux .desktop 文件已更新,以包含新的协议处理程序。 一些用于捆绑和分发应用的 Electron 工具可以为您处理这个问题。

Electron Forge

如果您使用 Electron Forge,请在您的 Forge 配置中调整 packagerConfig 以支持 macOS,并调整相应的 Linux makers 的配置以支持 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

针对 macOS 支持

如果您使用 Electron Packager 的 API,添加协议处理程序支持类似于 Electron Forge 的处理方式,只是 protocols 是传递给 packager 函数的 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}`))

如果您使用 Electron Packager 的 CLI,请使用 --protocol--protocol-name 标志。 例如

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

结论

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

// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell, dialog } = require('electron/main')
const path = require('node: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()
}

dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop().slice(0, -1)}`)
})

// 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)
})