Open external URLs from an Electron app

Oftentimes in an Electron app, you’ll want to open a URL that points to a page outside of your app. By default, the app will open the URL directly in your app rather than the user’s browser. To change this behavior, we first have to register a window open handler on your app’s BrowserWindow:

import { shell } from "electron";

mainWindow.webContents.setWindowOpenHandler((details) => {
  shell.openExternal(details.url); // Open URL in user's browser.
  return { action: "deny" }; // Prevent the app from opening the URL.

This handler prevents all window open requests from changing the URL inside your app, and instead causes the URL to open in the user’s browser. However, this only works if your links open new windows/tabs. You can have anchor tags with target="_blank", or call with a _blank target:

<!-- Allow the user to click and open a link. -->
<a href="" target="_blank">Some link</a>
// Open a URL programmatically."", "_blank");