【问题标题】:How to open links in default browser using Electron如何使用 Electron 在默认浏览器中打开链接
【发布时间】:2018-12-10 08:39:57
【问题描述】:

我正在使用一个简单的浏览器窗口,如下所示:

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)
})

每当我单击浏览器窗口中的链接时,都会创建一个电子浏览器窗口的新实例。是否可以使用默认系统浏览器打开链接? (chrome/firefox/vivaldi/等)

我已经阅读了这些资源以及其他资源。但没有一个取得任何成功:

Electron Browser-Window Doc

How do I open a url from on default OS browser?

编辑:

我已经尝试过了,它似乎是我找到的所有解决方案中最有可能奏效的,但它给了我:webContents.on is not a function

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();
}

谢谢

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    这些链接是&lt;a&gt;标签吗?

    如果是这样,这对我有用:

    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页面中的&lt;script&gt;标签中。
    • 是的,我就是这么想的。但是,它仍然给了我一个电子浏览器窗口
    • 奇怪.. 它为我打开了 chrome。尝试检查操作系统中的默认浏览器设置?
    • 是的...我可以发布我所有的 html 以便您查看
    • 当然..还有js
    【解决方案2】:

    您可以尝试使用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')
    })
    

    【讨论】:

    • 我已经尝试过了。让我知道我是否实施错误。为您更新代码。
    • 您的“app.js 建议”看起来不错(拼写错误和会话除外)。如果您加载一些常规 URL 而不是您自己的服务,我相信它会起作用。我想您应该确保在需要时从您的服务中发出“will-navigate”。
    • 非常适合我。电子版 2.0.8。
    • @mareoraft 感谢您的反馈,因此我最终放弃了这个项目。如果你设法让它工作,我会再试一次。知道为什么我得到webContents.on is not defined 吗?
    • @Joel 我认为您的“webContents”不是正确的变量。您说您通过const {webContents} = require('electron') 创建了变量。我和 pergy 都没有以这种方式访问​​ webContents。 webContents 是窗口对象的一个​​属性。所以你需要改用win.webContents.on(win.webContents 是该特定窗口 win 的网页内容。
    【解决方案3】:

    在尝试了上述几个导致我的答案的建议后,我采取了不同的方法,所以谢谢大家。我的项目有点不同:我使用 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>
    

    我希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 2020-11-27
      • 2018-05-02
      • 2015-11-30
      • 2012-07-18
      • 1970-01-01
      • 2012-08-11
      • 2015-08-21
      相关资源
      最近更新 更多