When developing desktop applications with Electron, handling external link navigation is common. Since Electron applications incorporate Chromium, clicking a link by default opens a new browser window inside the application to load the page, but this is often not the desired behavior. We prefer clicking links to open in the user's default browser. To achieve this, we can use the openExternal method from Electron's shell module.
Here are the specific implementation steps and example code:
Steps
-
Introduce the
shellmodule in your application: Electron'sshellmodule provides various desktop integration features, including opening files and links in external applications.javascriptconst { shell } = require('electron'); -
Handle link click events: When a user clicks a link, prevent the default behavior and use the
openExternalmethod to open the link.javascriptconst handleLinkClick = (event) => { event.preventDefault(); // Prevent default behavior const href = event.target.href; // Get the link URL shell.openExternal(href); // Open the link in the default browser }; -
Add event listeners to links: During page load or application startup, add click event listeners to all external links.
javascriptdocument.addEventListener('DOMContentLoaded', () => { const links = document.querySelectorAll('a[href^="http"]'); links.forEach(link => { link.addEventListener('click', handleLinkClick); }); });
Example
Suppose your Electron application has an HTML page containing some external links:
html<!DOCTYPE html> <html> <head> <title>My Electron Application</title> </head> <body> <h1>Welcome to my application</h1> <p><a href="https://www.example.com">Visit Example</a></p> <p><a href="https://www.google.com">Visit Google</a></p> <script src="renderer.js"></script> </body> </html>
In the renderer.js file, implement the code as follows:
javascriptconst { shell } = require('electron'); document.addEventListener('DOMContentLoaded', () => { const links = document.querySelectorAll('a[href^="http"]'); links.forEach(link => { link.addEventListener('click', (event) => { event.preventDefault(); const href = event.target.href; shell.openExternal(href); }); }); });
Using this approach, when a user clicks a link, their default browser opens the link instead of within the Electron application. This provides a more user-friendly browsing experience and leverages the full functionality of the browser.