site infoHacknerd | Tech Blog
blog cover

🚐 [Electron] 自定义协议

Electron

注册协议

javascriptCopy
// main.js

if (process.defaultApp) {
  if (process.argv.length >= 2) {
    app.setAsDefaultProtocolClient("${protocal name}", process.execPath, [path.resolve(process.argv[1])])
  }
} else {
  app.setAsDefaultProtocolClient("${protocal name}")
}

触发事件

windows 和 linux触发second-instance事件

javascriptCopy
// main.js

app.on('second-instance', (event, commandLine, workingDirectory) => {
  // 用户正在尝试运行第二个实例,我们需要让焦点指向我们的窗口
  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore()
    mainWindow.focus()
  }
  // 命令行是一个字符串数组,其中最后一个元素是深度链接的URL。
  dialog.showErrorBox('Welcome Back', `You arrived from: ${commandLine.pop()}`)
})

Mac 上触发open-url事件

javascriptCopy
// main.js

// 处理协议 在本例中,我们选择显示一个错误提示对话框。
app.on('open-url', (event, url) => {
  dialog.showErrorBox('欢迎回来', `导向自: ${url}`)
})

Electron-builder打包配置

package.json

jsonCopy
{
	...,
  "build": {
	  ...,
    "protocols": {
      "name": "${protocal name}",
      "schemes": ["${protocal}"]
    },
  }
}

使用协议

安装好后可以再,浏览器上输入${protocal name}://url 打开外部应用

Contents

  • 注册协议
  • 触发事件
  • Electron-builder打包配置
  • 使用协议

2024/06/19 02:29