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

Make a link from Electron open in browser

1个答案

1

In Electron applications, you may prefer to open certain links in the user's default browser rather than within the Electron window. To achieve this, you can use the shell module from Node.js, which is part of the electron package. Here is a simple example demonstrating how to open a link in the user's default browser:

javascript
const { shell } = require('electron'); // Open external link shell.openExternal('https://www.example.com');

In practice, you might want to bind this functionality to a click event, such as when the user clicks a link. Below is a possible HTML and JavaScript example illustrating how to implement this in an Electron application:

HTML:

html
<!-- Assume you have such a link --> <a href="https://www.example.com" id="external-link">Visit Example.com</a>

JavaScript:

javascript
const { shell } = require('electron'); document.getElementById('external-link').addEventListener('click', function(event) { event.preventDefault(); // Prevents the default behavior, i.e., opening the link in the Electron window const href = this.getAttribute('href'); shell.openExternal(href); // Opens the link in the user's default browser });

In this example, we first import the shell module. Then, we select an HTML link element with a specific id and add a click event listener. When the user clicks the link, the event.preventDefault() call prevents the default link opening behavior. Finally, shell.openExternal(href) opens the link in the user's default browser.

Ensure that you properly handle user input when opening external links in Electron and only open trusted links to avoid security risks.

2024年6月29日 12:07 回复

你的答案