Make a link from Electron open in browser

2019-02-07 17:22发布

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 ?

4条回答
我想做一个坏孩纸
2楼-- · 2019-02-07 18:03

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 = "#";
}
查看更多
该账号已被封号
3楼-- · 2019-02-07 18:18

There's a much better and simpler way, than what @Marcelo proposed, yet easier to implement for all links at once to what @zianwar proposed.

const shell = require('electron').shell;

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

NOTE: Requires jQuery.

查看更多
闹够了就滚
4楼-- · 2019-02-07 18:20

You can simply use :

require("shell").openExternal("http://www.google.com")
查看更多
再贱就再见
5楼-- · 2019-02-07 18:20

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.

查看更多
登录 后发表回答