javascript - 是否可以在Electron中过滤URL?

标签 javascript node.js electron

我有一个简单的 Electron 应用程序。它仅通过webview打开一个主URL。
现在可以使用,但是我想拥有某种白名单功能。仅允许一个URL并将用户从任何其他URL重定向到主URL。可以在Electron中完成吗?
谢谢你的帮助。
index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>1</title>
</head>
<body>

    <webview id="foo" src="https://www.google.com" style="display:inline-flex; width:100%; height:100%"></webview>

    <script>
        onload = () => {
            const webview = document.querySelector('webview')
        }
    </script>

</body>
</html>
main.js
const {app, BrowserWindow} = require('electron')

let mainWindow

function createWindow () {
    mainWindow = new BrowserWindow({
        webPreferences: {
            webViewTag: true
        },
        width: 1024, 
        height: 576,
        //frame: false,
        //fullscreen: true,
    })

    mainWindow.loadFile('index.html')
    mainWindow.webContents.loadURL('https://www.google.com').then(() => {
        const currentURL = mainWindow.webContents.getURL()
        console.log(currentURL)
    })
    
    // mainWindow.webContents.openDevTools()

    mainWindow.on('closed', function () {
    mainWindow = null
    })
}

app.on('ready', createWindow)

最佳答案

如果可能的话,应该避免使用<webview>
根据 <webview> tag docs:

Electron's webview tag is based on Chromium's webview, which is undergoing dramatic architectural changes. This impacts the stability of webviews, including rendering, navigation, and event routing. We currently recommend to not use the webview tag and to consider alternatives, like iframe, Electron's BrowserView, or an architecture that avoids embedded content altogether.


如果必须使用<webview>,那么您需要的是 will-navigate event:
onload = () => {
    const webview = document.querySelector('webview')

    webview.addEventListener('will-navigate', (e) => {
        const url = (new URL(e.url))

        // perform your login on `url`

        if (yourLogic)
            webview.loadURL(yourNewUrl)
    })
}

关于javascript - 是否可以在Electron中过滤URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65726295/

相关文章:

javascript - 悬停和嵌套列表 : which element is being hovered?

javascript - 使用 Jquery 将空格替换为 "&nbsp;"

node.js - 每服务器 NodeJS 配置

node.js - 如何在React中查看axios错误响应JSON

javascript - NodeJS + Socket IO 发送过多数据

electron - 控制台日志不再显示信息日志

javascript - reactjs 在 map 函数中从子更新父状态

javascript - 获取整型变量的值以进行动态加载

angular - Nx工作区+本地存储

javascript - 如何将 svg "rgb()"属性的随机数值放入 "fill"中?