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

问题描述 投票:1回答:3

我正在使用一个简单的浏览器窗口:

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

app.js建议:

const electron = require('electron');
const url = require('url');
const path = require('path');
const {app,BrowserWindow} = electron;
const {session} = require('electron')
// app.on('ready',function(){

// In the main process.
// const {BrowserWindow} = require('electron')

// Or use `remote` from the renderer process.
// const {BrowserWindow} = require('electron').remote
app.once('ready', () => {
  const handleRedirect = (e, url) => {
    if (url !== e.sender.getURL()) {
      e.preventDefault()
      shell.openExternal(url)
    }
  }


let win = new BrowserWindow({
  width: 500, 
  height: 613, 
  title: 'Rektron AB Chat',
  autoHideMenuBar:true,
  icon: path.join(__dirname, 'rektron.ico'),
  resizable:false,
  backgroundColor:"#2c2f33",
  webPreferences: {
    session : session,
    webSecurity: false,
  }
})
win.on('closed', () => {
  win = null
})

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

});

谢谢

node.js electron
3个回答
1
投票

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

0
投票

这些链接<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)
      })
   }
}

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>

我希望这有助于其他人。

© www.soinside.com 2019 - 2024. All rights reserved.