Electron页面跳转、浏览器打开链接和打开新窗口

xiaohai 2021-05-13 16:31:13 9945人围观 标签: Electron 
简介Electron页面跳转、浏览器打开链接和打开新窗口
一、a标签页面跳转

在渲染进程中,如果使用<a>标签可以进行页面跳转,这个跳转只是在当前窗口进行。使用方式如下:

<a href="./test.html">打开新窗口</a>
二、浏览器打开链接

如果我们要通过浏览器打开一个链接,那么可以通过Shell方式进行。首先要给<a>标签绑定一个事件,这里首先给a标签设置id,如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo1</title>
    <script src="index.js"></script>
</head>
<body>
    <div style='text-align:center;margin-top:109px;'>
        <p><a id="openUrl" href="https://www.baidu.com">浏览器打开新窗口</a></p>
    </div>
</body>
</html>

这里设置了id,并且指定了需要打开的链接地址。

在index.js文件中,我们给上面的标签绑定事件:

var { shell, fs } = require('electron')

window.onload = function () {

    //...其他代码

    var openUrl = document.querySelector('#openUrl')
    openUrl.onclick = function (e) {
        e.preventDefault()
        var href = this.getAttribute('href')
        shell.openExternal(href)
    }
}

运行后就可以在浏览器中打开了。

三、window.open打开窗口

在index.html中添加如下代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo1</title>
    <script src="index.js"></script>
</head>
<body>
    <div style='text-align:center;margin-top:109px;'>
        <p>
            <-- 如下代码 -->
            <button id="openUrl2">Open打开新窗口</button>
        </p>
    </div>
</body>
</html>

在index.js中添加如下代码:

var { shell, fs } = require('electron')

window.onload = function () {
    //其他代码
    var openUrl2 = document.querySelector('#openUrl2')
    openUrl2.onclick = function (e) {
        window.open('https://www.baidu.com')
    }
}