admin管理员组

文章数量:1134241

Is there any (simple/built-in way) to open a new browser (I mean default OS browser) window for a link from Electron instead of visiting that link inside your Electron app ?

Is there any (simple/built-in way) to open a new browser (I mean default OS browser) window for a link from Electron instead of visiting that link inside your Electron app ?

Share Improve this question edited Feb 23, 2016 at 14:52 saadel asked Jul 31, 2015 at 15:14 saadelsaadel 1,7571 gold badge14 silver badges19 bronze badges 2
  • 1 Does this answer your question? How can I force external links from browser-window to open in a default browser from Electron? – m4tt1mus Commented Mar 27, 2020 at 20:03
  • One of this one or the linked one from @m4tt1mus should be closed. They are exactly the same question. This was asked earlier - but I don't know what is the defining criteria. – icc97 Commented Aug 24, 2023 at 13:28
Add a comment  | 

14 Answers 14

Reset to default 94

You can simply use :

require("shell").openExternal("http://www.google.com")

EDIT: @Evgenii's answer is much better these days.

This answer is quite old and assumes you have jQuery.

const shell = require('electron').shell;
  
// assuming $ is jQuery
$(document).on('click', 'a[href^="http"]', function(event) {
    event.preventDefault();
    shell.openExternal(this.href);
});

Update

on('new-window'.. is deprecated since electron 22. use setWindowOpenHandler instead.

webContents.setWindowOpenHandler((details) => {
  return { action: 'deny' }
})

Check other answers. deprecation info: https://www.electronjs.org/docs/latest/breaking-changes#removed-webcontents-new-window-event

old Answer (pre electron 22)

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

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

My code snippet clue accordingly to the depreciations in Electron version ^12.0.0, put this code in your 'entry point' main.js (or whatever you call it):

const win = new BrowserWindow();
win.webContents.setWindowOpenHandler(({ url }) => {
    // config.fileProtocol is my custom file protocol
    if (url.startsWith(config.fileProtocol)) {
        return { action: 'allow' };
    }
    // open url in a browser and prevent default
    shell.openExternal(url);
    return { action: 'deny' };
});

Links must also have target="_blank".

In the view component use simple a link:

<a href="https://google.com" target="_blank" rel="noreferrer">
  <button type="button">
    button title
  </button>
</a>

And in file public/electron.js add default behavior for all a link navigations:

function createWindow() {
  ...
  // Open urls in the user's browser
  win.webContents.setWindowOpenHandler((edata) => {
    shell.openExternal(edata.url);
    return { action: "deny" };
  });
}

Some handy solutions can be found in this gist.

By listening on the body, the following solutions will work on <a> tags that may not yet exist when the JavaScript runs, but only appear in the DOM at a later time.

This one by luizcarraro requires jQuery:

$('body').on('click', 'a', (event) => {
  event.preventDefault();
  require("electron").shell.openExternal(event.target.href);
});

You can change the selector to target only certain links, e.g. '#messages-view a' or 'a.open-external'.

Here is an alternative without any library (derived from zrbecker's):

document.body.addEventListener('click', event => {
  if (event.target.tagName.toLowerCase() === 'a') {
    event.preventDefault();
    require("electron").shell.openExternal(event.target.href);
  }
});

Consult the gist for more examples.

To make all Electron links to open externally in the default OS browser you will have to add an onclick property to them and change the href property so it doesn't load anything in the Electron app.

You could use something like this:

aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
  aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
  aTags[i].href = "#";
}

But make sure the entire document has loaded before doing this otherwise it is not going to work. A more robust implementation would look like this:

if (document.readyState != "complete") {
  document.addEventListener('DOMContentLoaded', function() {
    prepareTags()
  }, false);
} else {
  prepareTags();
}

function prepareTags(){
  aTags = document.getElementsByTagName("a");
  for (var i = 0; i < aTags.length; i++) {
    aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
    aTags[i].href = "#";
  }
  return false;
}

Remember that if you load external files you will have to make them go through this process as well after they are fully loaded.

I use this method with Electron v.13.

We intercept the user's navigation (window.location) and open the URL in the default browser.

See the doc : https://www.electronjs.org/docs/latest/api/web-contents#event-will-navigate

const { shell } = require('electron');

window.webContents.on('will-navigate', function (e, url) {
    e.preventDefault();
    shell.openExternal(url);
});

On tsx syntax (Electron):

import { shell } from "electron";
shell.openExternal("http://www.google.com")

Update 2023

Since electron 22 on('new-window') is deprecated. You need to use setWindowOpenHandler and add a target="_black" to your links

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

To open an external link in an Electron's Project you will need the module Shell (https://www.electronjs.org/docs/api/shell#shell) and the method openExternal.

But if you are looking for an abstract way to implement that logic is by creating a handler for a custom target to your target attribute.

const {shell} = require('electron');

if (document.readyState != "complete") {
    document.addEventListener('DOMContentLoaded', function() {
        init()
    }, false);
} else {
    init();
}

function init(){
    handleExternalLinks();
    //other inits
}


function handleExternalLinks(){
    let links = document.getElementsByTagName('a')
    let a,i = 0;
    while (links[i]){
        a = links[i]
        //If <a target="_external">, so open using shell.
        if(a.getAttribute('target') == '_external'){
            a.addEventListener('click',(ev => {
                ev.preventDefault();
                let url = a.href;
                shell.openExternal(url);
                a.setAttribute('href', '#');
                return false;
            }))
        }
        console.log(a,a.getAttribute('external'))
        i++;
    }
}

To run an Electron project in your actual browser (Chrome, Mozilla, etc), add this to your script are external script:

aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
     aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
     aTags[i].href = "#";
}
const { shell } = require('electron')

shell.openExternal('https://github.com')

I have created a video on how to redirect users to browser from anywhere in the Electron application.

  1. First, make sure the URL starts with http/s
  2. Then, ensure event.preventDefault function has been called after shell.openExternal.
  3. Finally, target="_blank" should be placed in the <a.. tag of the html pages.

See the video clip for details. https://www.youtube.com/watch?v=wImCug-ZEOk

本文标签: javascriptMake a link from Electron open in browserStack Overflow