【问题标题】:Electron app.on("open-url") alternative for custom protocol in WindowsWindows 中自定义协议的 Electron app.on("open-url") 替代方案
【发布时间】:2019-11-01 09:25:47
【问题描述】:

我正在使用 Electron 开发一个应用程序,我需要在这个应用程序中处理一个自定义协议。
我为此使用app.setAsDefaultProtocolClient(PROTOCOL)

我在 macOS 上使用“open-url”通过我的自定义协议处理 URL,它运行顺利,但我无法在 Windows 上解决。我在 URL 中发送一些数据,所以仅仅打开窗口是行不通的。

我检查了this answer,但这在 2016 年得到了回答,现在不推荐使用 makeSingleInstance 方法。在文档中,它建议使用requestSingleInstanceLock,但它不接受任何回调或返回 URL。

那么如何在 macOS 和 Windows 中启用相同的功能?


代码

index.js

app.on('ready', () => createWindow(`file://${__dirname}/views/welcome.html`));

app.on('activate', () => {
  // eslint-disable-next-line no-shadow,global-require
  const { mainWindow } = require('./utils/createWindow');
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow(`file://${__dirname}/views/welcome.html`);
  }
});

app.on('open-url', handleOpenURL);

app.setAsDefaultProtocolClient(PROTOCOL);

handleOpenURL.js

module.exports = (e, data) => {
  e.preventDefault();
  // Some other Logic
  createWindow(URL);
}

【问题讨论】:

标签: javascript windows electron


【解决方案1】:

看看这个example 它是用角度和电子构建的。

您只需要确保自定义 uri 可以在 Windows 上运行:

首先,只有一个瞬间正在运行,通过检查app.requestSingleInstanceLock() 如果它是真的那么你需要退出应用程序app.quit()。因为我们只需要一个实例即可运行。其次,你应该处理second-instance事件app.on('second-instance', (event, args) => {})

const customSchemeName = 'x-company-app';
const primaryInstance = app.requestSingleInstanceLock();
if (!primaryInstance) {
        app.quit();
        return;
}

// The primary instance of the application will run this code, not the new  instance
app.on('second-instance', (event, args) => {
    // handle custom uri
}

...
// Register private URI scheme for the current user when running for the first time
app.setAsDefaultProtocolClient(customSchemeName);

// Handle custom uri requests against the running app on Mac OS
app.on('open-url', (event, customSchemeData) => {
    event.preventDefault();
    // handle the data
});
...

我在 Windows 上遇到了同样的问题,这为我解决了这个问题,我已经对其进行了测试并且它可以工作。 归功于 Gary Archer。

【讨论】:

  • 问题是,这个事件second-instance 没有被触发。我尝试添加日志并在生产版本中添加了dialog,但它不起作用。
猜你喜欢
  • 2020-02-09
  • 2020-10-06
  • 2018-03-09
  • 2023-03-27
  • 2016-11-27
  • 2010-09-09
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多