Windows 中自定义协议的 Electron app.on("open-url") 替代方案

Apa*_*hah 4 javascript windows electron

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

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

我检查了这个答案,但这是在 2016 年回答的,并且该方法makeSingleInstance现已弃用。在文档中,它建议使用requestSingleInstanceLock,但它不接受任何回调或返回 URL。

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


代码

索引.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);
Run Code Online (Sandbox Code Playgroud)

处理OpenURL.js

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

小智 8

看一下这个例子,它是用 Angular 和 Electron 构建的。

您只需确保以下内容即可使自定义 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
});
...
Run Code Online (Sandbox Code Playgroud)

我在 Windows 上遇到了同样的问题,这为我解决了它,我已经测试过它并且它有效。学分归加里·阿切尔所有。