将超文本 link 对外部 URL 的点击重新路由到其他浏览器而不是 Electron 应用程序

Re-route hypertext link clicks to external URLs to another browser than the Electron app

我有一个 Electron BrowserWindow,其中包含 UI 个元素和一个 BrowserView 创建的元素:

bv = createBrowserView('https://example.com');
...
browserWindow.setBrowserView(bv);

如何将此 BrowserView 限制为 ***.example.com/*** 形式的 URL,即留在域 example.com 上?

更准确地说,如果用户点击超文本 link 走出这个域,它应该在外部应用程序中打开,例如系统的默认浏览器,而不是在 Electron 应用程序中。

如何使用 Electron BrowserView 做到这一点?

这个有效:

bv.webContents.on('will-navigate', (event, url) => {
    console.log('will-navigate', url);
    if (condition_on_the_url) {
        shell.openExternal(url);  // length limit on Windows: https://www.electronjs.org/docs/api/shell#shellopenexternalurl-options
        event.preventDefault();
    }
});

注意:事件 new-window 在用户点击带有 target="_blank" 的 link 时也很有用。