M
M
Mikhail A.2021-01-14 22:45:41
JavaScript
Mikhail A., 2021-01-14 22:45:41

How to filter URL in Electron?

The application is a simple URL opener, via a webview.

There is a need to close access to some pages (addresses). So that if you go to an unwanted address, Electron would redirect to the main page.

Is it possible to do similar filtering in Electron?

index.html

<!DOCTYPE html>
<html lang="ru">
<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)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
@
@imegaded, 2021-01-15
@mg_abr

In my case, there was a need to open all third-party links in the browser (not electron). There is access to the url, do whatever processing your heart desires =)

import open from 'open';
...
...
...
app.on('web-contents-created', (_event, contents) => {
  contents.on('new-window', (e, urlLink) => {
    e.preventDefault();
    open(urlLink);
  });
  contents.on('will-navigate', (e, urlLink) => {
    if (urlLink !== contents.getURL()) {
      e.preventDefault();
      open(urlLink);
    }
  });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question