How can I force external links from browser-window to open in a default browser from Electron?

I'm using the BrowserWindow to display an app and I would like to force the external links to be opened in the default browser. Is that even possible or I have to approach this differently?


Solution 1:

I came up with this, after checking the solution from the previous answer.

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

According to the electron spec, new-window is fired when external links are clicked.

NOTE: Requires that you use target="_blank" on your anchor tags.

Solution 2:

new-window is now deprecated in favor of setWindowOpenHandler in Electron 12 (see https://github.com/electron/electron/pull/24517).

So a more up to date answer would be:

mainWindow.webContents.setWindowOpenHandler(({ url }) => {
  shell.openExternal(url);
  return { action: 'deny' };
});

Solution 3:

If you're not using target="_blank" in your anchor elements, this might work for you:

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

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