Electron中如何通过Deep Link实现从index.html跳转至index2.html
解决方案
要实现触发localm://okay时切换到index2.html,需要覆盖应用未启动时通过深度链接打开、应用已运行时触发深度链接两种场景,以下是修改后的完整代码及说明:
修改后的代码
let deeplinkingUrl; let window; app.setAsDefaultProtocolClient('localm'); // 统一处理深度链接逻辑 app.on('open-url', handleDeepLink); // Windows/Linux下,应用已运行时触发协议会启动新实例,需通过该事件捕获链接 app.on('second-instance', (event, commandLine) => { const url = commandLine.pop(); if (url.startsWith('localm://')) { handleDeepLink(event, url); } // 恢复并聚焦窗口 if (window) { if (window.isMinimized()) window.restore(); window.focus(); } }); function handleDeepLink(event, url) { event.preventDefault(); deeplinkingUrl = url; // 窗口已存在时直接切换页面 if (window) { switchPageByDeepLink(url); } } function switchPageByDeepLink(url) { if (url === 'localm://okay') { window.loadURL(`file://${__dirname}/WEB/index2.html`); } else { // 其他链接默认加载首页,可按需扩展规则 window.loadURL(`file://${__dirname}/WEB/index.html`); } } // 🌖 M A I N W I N D O W app.on('ready', () => { window = new BrowserWindow({ autoHideMenuBar: true, width: 1180, height: 768, minWidth: 1170, minHeight: 768, title: "LocalMiner", icon: __dirname + '/assets/logo.ico', titleBarStyle: "hidden", frame: false, titleBarOverlay: { color: "#1f2937a4", symbolColor: "#fff", }, webPreferences: { // devTools: false, nodeIntegration: true, contextIsolation: false, webviewTag: true, } }); // 启动时检查深度链接,决定初始加载页面 if (deeplinkingUrl === 'localm://okay') { window.loadURL(`file://${__dirname}/WEB/index2.html`); } else { window.loadURL(`file://${__dirname}/WEB/index.html`); } ipcMain.on("download", (event, info) => { info.properties.onProgress = status => window.webContents.send("download progress", status); download(BrowserWindow.getFocusedWindow(), info.url, info.properties) .then(dl => window.webContents.send("download complete", dl.getSavePath())); }); LocalApi(); }); // Windows下确保单实例运行,避免重复启动 if (process.platform === 'win32') { const gotTheLock = app.requestSingleInstanceLock(); if (!gotTheLock) { app.quit(); } }
关键改动说明
- 统一链接处理逻辑:提取
handleDeepLink函数,避免macOS、Windows/Linux平台的代码重复 - 覆盖多平台场景:添加
second-instance事件监听,解决Windows/Linux下应用已运行时触发协议的问题 - 页面切换逻辑封装:
switchPageByDeepLink函数集中管理链接与页面的映射,方便后续扩展其他深度链接规则 - 启动时的初始页面判断:在
ready事件中先检查深度链接,决定应用启动时加载的页面 - 用户体验优化:触发深度链接时自动恢复、聚焦窗口
注意事项
- 确认
index2.html路径正确,与index.html处于同一WEB目录下 - 打包应用时,需在打包配置(如electron-builder的
protocols字段)中添加协议关联,确保系统能正确识别localm协议
内容的提问来源于stack exchange,提问作者HEALER
相关产品推荐
相关产品推荐

