深层链接
🌐 Deep Links
概述
🌐 Overview
本指南将带你了解如何将你的 Electron 应用设置为特定协议的默认处理程序。
🌐 This guide will take you through the process of setting your Electron app as the default handler for a specific protocol.
在本教程结束时,我们将将应用设置为拦截并处理 任何以特定协议开头的点击URL。本指南中,协议内容 我们将使用“'electron-fiddle://'”。
🌐 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.js)
🌐 Main Process (main.js)
首先,我们将从 electron 导入所需的模块。这些模块有助于控制应用的生命周期并创建原生浏览器窗口。
🌐 First, we will import the required modules from electron. These modules help
control our application lifecycle and create a native browser window.
const { app, BrowserWindow, shell } = require('electron')
const path = require('node:path')
接下来,我们将注册我们的应用以处理所有“electron-fiddle://”协议。
🌐 Next, we will proceed to register our application to handle all "electron-fiddle://" protocols.
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 文件。
🌐 We will now define the function in charge of creating our browser window and load our application's index.html file.
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,并告诉我们的应用如何处理外部协议被点击的事件。
🌐 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.
这段代码在 Windows 和 Linux 上与 macOS 不同。这是因为这两个平台会触发 second-instance 事件,而不是 open-url 事件,并且 Windows 需要额外的代码才能在同一个 Electron 实例中打开协议链接的内容。更多内容请点击这里了解。
🌐 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 和 Linux 代码:
🌐 Windows and Linux 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()
}
// 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 代码:
🌐 macOS 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
在 macOS 和 Linux 上,此功能仅在应用打包后才会生效。在开发进程中通过命令行启动应用时,该功能将无法使用。当你打包应用时,需要确保 macOS 的 Info.plist 文件和 Linux 的 .desktop 文件已更新,以包含新的协议处理程序。一些用于打包和分发应用的 Electron 工具会为你处理这部分内容。
🌐 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
如果你使用的是 Electron Forge,请在你的 Forge 配置 中调整 packagerConfig 以支持 macOS,并为 Linux 支持配置相应的 Linux 制作器
(请注意,下面的示例仅显示添加配置更改所需的最基本内容):
🌐 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):
{
"config": {
"forge": {
"packagerConfig": {
"protocols": [
{
"name": "Electron Fiddle",
"schemes": ["electron-fiddle"]
}
]
},
"makers": [
{
"name": "@electron-forge/maker-deb",
"config": {
"mimeType": ["x-scheme-handler/electron-fiddle"]
}
}
]
}
}
}
Electron 打包工具
🌐 Electron Packager
对于 macOS 支持:
🌐 For macOS support:
如果你正在使用 Electron Packager 的 API,添加对协议处理程序的支持与处理 Electron Forge 类似,只是 protocols 是作为选项的一部分传递给 packager 函数的。
🌐 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.
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 的命令行工具,请使用 --protocol 和 --protocol-name 标志。例如:
🌐 If you're using Electron Packager's CLI, use the --protocol and --protocol-name flags. For
example:
npx electron-packager . --protocol=electron-fiddle --protocol-name="Electron Fiddle"
结论
🌐 Conclusion
在启动你的 Electron 应用后,你可以在浏览器中输入包含自定义协议的 URL,例如 "electron-fiddle://open",并观察应用会做出响应并显示错误对话框。
🌐 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.
- main.js
- preload.js
- index.html
- renderer.js
// 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)
})
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('shell', {
open: () => ipcRenderer.send('shell:open')
})
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<title>app.setAsDefaultProtocol Demo</title>
</head>
<body>
<h1>App Default Protocol Demo</h1>
<p>The protocol API allows us to register a custom protocol and intercept existing protocol requests.</p>
<p>These methods allow you to set and unset the protocols your app should be the default app for. Similar to when a
browser asks to be your default for viewing web pages.</p>
<p>Open the <a href="https://www.electronjs.org/docs/latest/api/protocol">full protocol API documentation</a> in your
browser.</p>
-----
<h3>Demo</h3>
<p>
First: Launch current page in browser
<button id="open-in-browser" class="js-container-target demo-toggle-button">
Click to Launch Browser
</button>
</p>
<p>
Then: Launch the app from a web link!
<a href="electron-fiddle://open">Click here to launch the app</a>
</p>
----
<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
as the default for <code>electron-fiddle://</code>. The demo button above will launch a page in your default
browser with a link. Click that link and it will re-launch this app.</p>
<h3>Packaging</h3>
<p>This feature will only work on macOS 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 <code>plist</code>
for the app is updated to include the new protocol handler. If you're using <code>@electron/packager</code> then you
can add the flag <code>--extend-info</code> with a path to the <code>plist</code> you've created. The one for this
app is below:</p>
<p>
<h5>macOS plist</h5>
<pre><code>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>electron-api-demos</string>
</array>
<key>CFBundleURLName</key>
<string>Electron API Demos Protocol</string>
</dict>
</array>
<key>ElectronTeamID</key>
<string>VEKTX9H2N7</string>
</dict>
</plist>
</code>
</pre>
<p>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All APIs exposed by the context bridge are available here.
// Binds the buttons to the context bridge API.
document.getElementById('open-in-browser').addEventListener('click', () => {
window.shell.open()
})