如何在Electron中使用默认浏览器打开链接

6
我正在使用一个简单的browserWindow,如下所示:
let win = new BrowserWindow({
  width: 500, 
  height: 613, 
  title: 'My App',
  autoHideMenuBar:true,
  icon: path.join(__dirname, 'logo.ico'),
  resizable:false,
  backgroundColor:"#2c2f33",
  webPreferences: {
    session : session,
    webSecurity: false,
  }
})
win.on('closed', () => {
  win = null
})

// Load a remote URL
win.loadURL('http://192.168.40.189:1337')
session.fromPartition('persist:name');
session.defaultSession.cookies.get({}, (error, cookies) => {
  console.log(error, cookies)
})

每当我在浏览器窗口中点击链接,就会创建一个新的Electron BrowserWindow实例。是否可以使用默认的系统浏览器打开链接?(chrome/firefox/vivaldi等)
我已阅读过以下资源,但没有取得任何成功: Electron Browser-Window Doc 如何在默认操作系统浏览器上打开URL? 编辑:
我尝试了这个解决方案,它似乎是所有我找到的解决方案中最有可能奏效的,但它给了我:webContents.on不是一个函数。
const {webContents} = require('electron')
var handleRedirect = (e, url) => {
  if(url != webContents.getURL()) {
    e.preventDefault()
    require('electron').shell.openExternal(url)
  }
}

webContents.on('will-navigate', handleRedirect)
webContents.on('new-window', handleRedirect)

HTML:

<!DOCTYPE html>
<html lang="en">
<head>

    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="/css/normalize.css">
            <link rel="stylesheet" href="/css/main.css">

</head>
<body>
    <div id="loader-wrapper">
        <div id="loader"></div>
        <div class="loader-section section-left"></div>
        <div class="loader-section section-right"></div>
    </div>
    <div class="chat">
        <div class="chat-header clearfix">
                <div class="chat-about">
            </div>
                <i class="fa fa-star"></i>
        </div> <!-- end chat-header -->
        <div class="chat-history">
            <ul id="content"></ul>

        </div> <!-- end chat-history -->
        <div class="chat-message clearfix">
            <input type="text" id="input" class=" message-to-send" tabindex="1" disabled="disabled" placeholder="Enter name" />
        </div>
    </div>
    <div class="chat-num-messages" id="status" style="display: none!important;">Connecting...</div>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
    <script type="text/javascript" src="/chat-frontend.js"></script>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    <script type="text/javascript">
        const shell = require('electron').shell

        const links = document.querySelectorAll('a[href]')

        Array.prototype.forEach.call(links, function (link) {
           const url = link.getAttribute('href')
           if (url.indexOf('http') === 0) {
              link.addEventListener('click', function (e) {
                  e.preventDefault()
                  shell.openExternal(url)
              })
           }
        })
            </script>
    <script src="js/vendor/modernizr-2.6.2.min.js"></script>
</body>
</html>

JS前端:

// "use strict";

// for better performance - to avoid searching in DOM
const inputElement = document.getElementById('input');
const contentElement = document.getElementById('content');
const statusElement = document.getElementById('status');
var userName = document.getElementById('status');

// my color
var myColor = false;
// my name 
var myName = false;

// if mozilla, use built in.
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
  contentElement.innerHTML = "<p>Sorry, your browser doesn't support websocket.</p>";
  inputElement.style = "display: none";
  statusElement.style = "display: none";
}
// open connection
const connection = new WebSocket('ws://192.168.40.189:1337');

connection.addEventListener('open', function(e) {
  inputElement.removeAttribute('disabled');
  statusElement.innerHTML = ' ';
});

connection.addEventListener('error', function (error) {
  contentElement.innerHTML = '<p>Sorry, but there\'s some problem with your connection, or the server is down.</p>';
});
connection.addEventListener('message', function (message) {
  var json;
  try {
    json = JSON.parse(message.data);
  } catch (e) {
    console.log('Invalid JSON: ', message.data);
    return;
  }
  if (json.type === 'color') {
    myColor = json.data;
    statusElement.innerHTML = myName + '';
    statusElement.style.color = myColor;
    inputElement.removeAttribute('disabled');
    userName = userName;
  } else if (json.type === 'history') {
    for (var i=0; i < json.data.length; i++) {
      var str = json.data[i].text;
      var strChanged  = str.replace(/https?:\/\/[^ ]+/g, '<span class="linkIsHere">➜</span><a target="_blank" href="$&">[Link]</a>'); // match any word until space
      addMessage(json.data[i].author, strChanged, json.data[i].color, new Date(json.data[i].time));
    }
  } else if(json.type === 'message' && (json.data.author != userName)){
    // console.log("author: "+ json.data.author + userName.value);
      var str = json.data.text;
      var strChanged  = str.replace(/https?:\/\/[^ ]+/g, '<span class="linkIsHere">➜</span><a target="_blank" href="$&">[Link]</a>'); // match any word until space
      addMessage(json.data.author,strChanged,json.data.color, new Date(json.data.time));
    }
  else if (json.type === 'message' && json.data.text.length > 60) { //spam protection....
    inputElement.value = "Denna checken gjordes speciellt för Christian...";
  }
   else if (json.type === 'message') {
    // standard message.
    inputElement.removeAttribute('disabled');
    // convert urls to links.
    var str = json.data.text;
    var strChanged  = str.replace(/https?:\/\/[^ ]+/g, '<span class="linkIsHere">➜</span><a target="_blank" href="$&">[Link]</a>'); // match any word until space
    addMessageRight(json.data.author, strChanged, json.data.color, new Date(json.data.time));
  }
   else {
    console.log('Hmm..., I\'ve never seen JSON like this:', json);
  }
});


//username cookie
 function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) != 0) return nameEQ.match("([^=]*)")[i];
    console.log(nameEQ.match("([^=]*)")[i]);
    }
    return nameEQ.match("([^=]*)");
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
/**
 * Send message when user presses Enter key
 */

//Cookie Check
 if(readCookie(document.cookie) != ""){
  var listener = function(){
    var myName = ' ';
    myName = readCookie(document.cookie); 
    connection.send(myName); 
    console.log("HE222EEJ: ")
    inputElement.setAttribute('placeholder','Send Message...'); 
    document.removeEventListener('click',listener,true);
  };
  document.addEventListener('click',listener,true);

  // connection.send(msg);
}
if(getCookie(document.cookie) == null){
  console.log("HEE333EJ: ")
input.addEventListener('keydown', function(e) {
  if (e.keyCode === 13) {
    const msg = inputElement.value;
    if (!msg) {
      return;
    }
      connection.send(msg);
      inputElement.value = '';
      inputElement.setAttribute('placeholder','Send Message...');

    if(!myName && msg.length > 20){inputElement.value="Sluta nu Christian...";}
      if(myName === false){
        myName = msg;
        userName = myName;
        createCookie(userName,userName,7);
      }
    }
    else{
      return;
    }
});
}
/* om det är connection-problem */
setInterval(function() {
  if (connection.readyState !== 1) {
    statusElement.innerHTML = 'ERROR';
    inputElement.setAttribute('disabled', 'disabled');
    inputElement.value = 'Unable to communicate with the WebSocket server.';
  }
}, 3000);

/**
 * Add message to the chat window
 */
function addMessage(author, message, color, dt) {
  contentElement.innerHTML += `<li class="clearfix">
                                <div class="message-data">
                                  <span class="message-data-name">
                                    <i class="fa fa-circle online"></i>`
                                    +author+
                                  `</span>
                                  <span class="message-data-time">`
                                    + (dt.getHours() < 10 ? '0'
                                    + dt.getHours() : dt.getHours()) + ':'
                                    + (dt.getMinutes() < 10
                                    ? '0' + dt.getMinutes() : dt.getMinutes())+
                                  `</span>
                                </div>`
                                +`<div class="message my-message" style="background:`+color+`;--my-color-var:`+color+`;">`+message+`
                                </div>
                                </li>`;
        contentElement.scrollIntoView({block: "end"}); //gjord speciellt för christian.
}

function addMessageRight(author, message, color, dt) {
  contentElement.innerHTML += `<li class="clearfix">
                                <div class="message-data align-right">
                                  <span class="message-data-time">` + (dt.getHours() < 10 ? '0'+ dt.getHours() : dt.getHours()) + ':'+ (dt.getMinutes() < 10? '0' + dt.getMinutes() : dt.getMinutes())+`</span>
                                  <span class="message-data-name">` +author+`</span><i class="fa fa-circle online"></i>
                                </div>`
                                +`<div class="message other-message float-right" style="background:`+color+`;--my-other-color-var:`+color+`;">`+message+`
                                </div>
                                </li>`;
        contentElement.scrollIntoView({block: "end"});
        var audio = new Audio('notification.mp3');
        audio.play();
}

谢谢

4个回答

13

你可以尝试使用webContents的类实例方法来完成这个操作,而不是使用静态函数。

const { app, BrowserWindow, shell } = require('electron')

app.once('ready', () => {
  const handleRedirect = (e, url) => {
    if (url !== e.sender.getURL()) {
      e.preventDefault()
      shell.openExternal(url)
    }
  }
  const win = new BrowserWindow()
  // Instead bare webContents:
  win.webContents.on('will-navigate', handleRedirect)
  win.loadURL('http://google.com')
})

我已经尝试过了。如果我实现有误,请告诉我。我会为您更新代码。 - Joel
你的“app.js建议”看起来不错(除了错别字和会话)。我相信如果您加载一些常规URL而不是自己的服务,它肯定可以工作。我猜当您需要时,您应该确保从您的服务中发出“will-navigate”。 - pergy
对我来说运行得非常好。Electron版本为2.0.8。 - mareoraft
@mareoraft 感谢您的反馈,但最终我还是放弃了这个项目。如果您成功解决了问题,我会再次尝试。不知道为什么我会在我的情况下得到 webContents.on is not defined 的错误信息? - Joel
1
@Joel,我认为你的“webContents”变量不正确。你说你是通过 const {webContents} = require('electron') 创建的变量。我和 pergy 都没有以这种方式访问 webContents。webContents 是您窗口对象的属性。因此,您需要使用 win.webContents.on( 来代替。win.webContents是该特定窗口 win 的 Web 内容。 - mareoraft
@Joel,Mareoraft所说的正是我所谓的“类实例方法而不是静态函数”。(代码也展示了这些表达式的含义) - pergy

3
这对我很有帮助。
mainWindow.webContents.on('new-window', function(e, url) {
  e.preventDefault();
  require('electron').shell.openExternal(url);
});

参考:这里


1

这些链接是<a>标签吗?

如果是的话,这个方法对我有效:

const shell = require('electron').shell

const links = document.querySelectorAll('a[href]')

Array.prototype.forEach.call(links, function (link) {
   const url = link.getAttribute('href')
   if (url.indexOf('http') === 0) {
      link.addEventListener('click', function (e) {
          e.preventDefault()
          shell.openExternal(url)
      })
   }
})

这段文字来自 Electron API Demos

编辑: 对于新链接,可以尝试类似这样的格式(我没有测试过):

function addMessage(author, message, color, dt) {
  contentElement.innerHTML += `<li class="clearfix">
                                <div class="message-data">
                                  <span class="message-data-name">
                                    <i class="fa fa-circle online"></i>`
                                    +author+
                                  `</span>
                                  <span class="message-data-time">`
                                    + (dt.getHours() < 10 ? '0'
                                    + dt.getHours() : dt.getHours()) + ':'
                                    + (dt.getMinutes() < 10
                                    ? '0' + dt.getMinutes() : dt.getMinutes())+
                                  `</span>
                                </div>`
                                +`<div class="message my-message" style="background:`+color+`;--my-color-var:`+color+`;">`+message+`
                                </div>
                                </li>`;
        changeLinkBehaviour();
        contentElement.scrollIntoView({block: "end"}); //gjord speciellt för christian.
}


function changeLinkBehaviour(){
 var link = contentElement.findElementsByClassName("message my-message")[0].querySelectorAll('a[href]')[0];
  //repetition of code I pasted eariler:
 const url = link.getAttribute('href')
   if (url.indexOf('http') === 0) {
      link.addEventListener('click', function (e) {
          e.preventDefault()
          shell.openExternal(url)
      })
   }
}

在对应于浏览器窗口的HTML页面中的<script>标签中。 - Ray
是的,那就是我想到的。但是,它仍然给了我一个electron-browser-window。 - Joel
奇怪..对我来说它在Chrome中打开。试试检查你的操作系统中的默认浏览器设置? - Ray
当然,还有 JavaScript。 - Ray
@Joel 编辑了我的答案,只是一个草稿。不确定它是否有效。 - Ray
显示剩余6条评论

0
在尝试了以上几种建议后,我采用了不同的方法,找到了我的答案,感谢大家。我的项目有一点不同:我使用Vue和Vuetify,以及Pug来实现更轻松的模板化。
首先是模板(只展示顶部以说明链接)。
<template lang="pug">
    div(style="height:220px;")
        v-card(height="220").ma-2
            v-layout(row wrap)
                v-flex(xs4)
                    div.mt-2.ml-2
                        a(@click="openExternalLink(twitterLink)")
                            v-avatar(size="80px" slot="activator")
                                v-img(src="https://abs.twimg.com/sticky/default_profile_images/default_profile.png" height="80px" contain alt="member.fullName")

为链接添加了点击监听器

脚本标签:

<script lang="ts">
import Vue from 'vue'
import { shell } from 'electron'

export default Vue.extend({
    props: ['member'],
    methods: {
        openExternalLink(link: string) {
            console.log(link)
            shell.openExternal(link)
        }
    },
    computed: {
        twitterLink() {
            const link: string = 'https://twitter.com/' + this.member.twitterHandle
            return link
        }
    }
})
</script>

我希望这能帮助其他人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接