Mikhail A.
Mikhail A.

Reputation: 1

It's possible to filter URLs in Electron?

I have a simple Electron App. It only opens one main URL via webview.

It works now, but I would like to have some kind of whitelist functionality. To allow only one URL and redirect users from any other urls to the main url. Can it be done in Electron?

Thanks for any help.

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)

Upvotes: 0

Views: 712

Answers (1)

Justin Taddei
Justin Taddei

Reputation: 2276

If as all possible, you should avoid using <webview>.
Per the <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.

If you must use <webview>, what you are looking for is the 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)
    })
}

Upvotes: 1

Related Questions