Saltar al contenido principal

Deep Links

Descripción general

Esta guía le llevará a través del proceso de establecer su aplicación Electron como el manejador predeterminado para un protocolo especifico.

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://".

Ejemplos

Main Process (main.js)

Primero, importaremos los módulos requeridos desde electron. Estos módulos ayudan a controlar el ciclo de vida de nuestra aplicación y crear una ventana del navegador nativa.

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

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

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

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 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. Lea más sobre esto aquí.

Windows and Linux code:

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
app.quit()
} else {
app.on('second-instance', (event, commandLine, workingDirectory) => {
// Alguien trata de correr una segunda instancia, debemos enfocar nuestra ventana.
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 code:

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Algunas APIs pueden solamente ser usadas despues de que este evento ocurra.
app.whenReady().then(() => {
createWindow()
})

// Maneja protocolo. En este caso, elegimos mostrar una Caja de Error.
app.on('open-url', (event, url) => {
dialog.showErrorBox('Welcome Back', `You arrived from: ${url}`)
})

Finalmente, agregaremos un poco de código adicional para manejar cuando alguien cierra nuestra aplicación.

// Quit when all windows are closed, except on macOS. Allí, es común
// para que las aplicaciones y su barra de menú permanezcan activas hasta que el usuario salga
// explicitamente con Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit()
})

Notas importantes

Embalaje

En macOS y Linux, esta característica solo funcionará cuando tu aplicación esté empaquetada. No funcionará si se inicia desde la línea de comandos durante el desarrollo. Cuando empaquetes tu aplicación necesitarás asegurarte de que los archivos Info.plist de macOS y los archivos .desktop de Linux para la aplicación están actualizados para incluir el nuevo manejador de protocolo. Algunas de las herramientas de Electron para empaquetar y distribuir aplicaciones manejan esto para ti.

Electron Forge

Si estás utilizando Electron Forge, ajuste el packagerConfig para soporte de macOS, y la configuración para los creadores apropiados de Linux para el soporte de Linux, en tu Configuración Forge (tenga en cuenta que el siguiente ejemplo solo muestra el mínimo necesario para agregar los cambios de configuración):

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

Empaquetador Electron

Para soporte de macOS:

Si estás utilizando las APIs de Electron Packager, agregar soporte para manejadores de protocolo es similar a como se hace en Electron Forge, excepto que protocols es parte de las opciones de Packager pasadas a la función 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}`))

Si estás utilizando el CLI de Electron Packager, use las banderas --protocol y --protocol-name. Por ejemplo:

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

Conclusión

Después de iniciar su aplicación Electron, puedes introducir la URL en tu navegador que contiene el protocolo URL personalizado, por ejemplo, "electron-fiddle://open" y observe que la aplicación responderá y mostrará un cuadro de dialogo de error.

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