如何从浏览器窗口强制外部链接在Electron的默认浏览器中打开?

Lip*_*pis 38 node.js electron

我正在使用BrowserWindow来显示应用程序,我想强制在默认浏览器中打开外部链接.这是可能的还是我必须以不同的方式处理这个问题?

小智 80

在检查了上一个答案的解决方案后,我想出了这个.

mainWindow.webContents.on('new-window', function(e, url) {
  e.preventDefault();
  require('electron').shell.openExternal(url);
});
Run Code Online (Sandbox Code Playgroud)

根据电子规格,new-window点击外部链接时会触发.

注意:需要您target="_blank"在锚标签上使用.

  • `main`是使用`new BrowserWindow()`创建浏览器窗口时返回的窗口 (5认同)
  • 当`target`设置为`_blank`时,"new-window"不会触发吗? (3认同)
  • Electron 12 中已弃用 `new-window`。请参阅 /sf/answers/4718645641/ (3认同)
  • 代替给我抛出错误的 `require('shell')`,我能够使用 `electron.shell.openExternal(url);` 使其工作 (2认同)

nii*_*ani 6

如果您没有target="_blank"anchor元素中使用,这可能对您有用:

  const shell = require('electron').shell;

  $(document).on('click', 'a[href^="http"]', function(event) {
    event.preventDefault();
    shell.openExternal(this.href);
  });
Run Code Online (Sandbox Code Playgroud)

  • 这假设我想象中的JQuery? (2认同)

Cet*_*thy 5

从接受的答案中改进;

  1. 链接必须是target="_blank"
  2. 添加background.js(或您创建窗口的任何地方):

    window.webContents.on('new-window', function(e, url) {
      // make sure local urls stay in electron perimeter
      if('file://' === url.substr(0, 'file://'.length)) {
        return;
      }
    
      // and open every other protocols on the browser      
      e.preventDefault();
      shell.openExternal(url);
    });
    
    Run Code Online (Sandbox Code Playgroud)

注意:为了确保所有应用程序窗口的这种行为,应该在每个窗口创建后运行此代码。


the*_*ire 5

new-window现在setWindowOpenHandler在 Electron 12 中被弃用(参见https://github.com/electron/electron/pull/24517)。

因此,更新的答案是:

mainWindow.webContents.setWindowOpenHandler(({ url }) => {
  shell.openExternal(url);
  return { action: 'deny' };
});
Run Code Online (Sandbox Code Playgroud)

  • 确保您从 Electron 导入 `shell`: const { shell } = require('electron') https://www.electronjs.org/docs/latest/tutorial/security#how-12 (4认同)
  • @DoneDeal0 您需要添加“https://”以使其成为 URL。 (2认同)
  • 如果您使用的是 es6,请使用“import { shell } from 'electron'”导入 shell (2认同)