Make a link from Electron open in browser

前端 未结 6 1391
庸人自扰
庸人自扰 2020-12-15 15:21

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 ?

6条回答
  •  既然无缘
    2020-12-15 16:02

    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.

提交回复
热议问题