乐闻世界logo
搜索文章和话题

How to open links in default browser using Electron

1个答案

1

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

  1. Introduce the shell module in your application: Electron's shell module provides various desktop integration features, including opening files and links in external applications.

    javascript
    const { shell } = require('electron');
  2. Handle link click events: When a user clicks a link, prevent the default behavior and use the openExternal method to open the link.

    javascript
    const 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 };
  3. Add event listeners to links: During page load or application startup, add click event listeners to all external links.

    javascript
    document.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:

javascript
const { 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.

2024年6月29日 12:07 回复

你的答案