Electron: prevent / cancel page navigation

2019-07-15 13:09发布

问题:

Is there anyway to prevent or cancel page navigation in electron?

win.webContents.on('did-start-loading', function(event, url) {
    if (event.sender.getURL().startsWith('http://xyz')) {
        event.preventDefault();
    }
})

The code above doesn't work since the event handler gets executed while the page keeps on navigating away.

Similarly, I'd also like to do the same for event 'did-get-redirect-request', to prevent certain redirect from happening.

Many thanks

回答1:

You can use the will-navigate event to stop navigation.

You can also prevent requests (including redirects) using webRequest.onBeforeRequest():

const {session} = require('electron')
const ses = session.defaultSession
const urlToBlock = 'whatever'
ses.webRequest.onBeforeRequest((details, callback) => {
if (details.url === urlToBlock) // cancel the request
  callback({ cancel: true })
else // let the request happen
  callback({})
})

If you want to block all redirects you can add a listener to webRequest.onBeforeRedirect() and add the redirect URL to a list of blocked URLs that you can then check in the listener you add to webRequest.onBeforeRequest().



回答2:

In my scenerio I've fixed it like below

// just for demonstration what is mainWindow like
let mainWindow: BrowserWindow;

mainWindow.webContents.on('new-window', (event, url) => {
  if (url.indexOf('#localhost/orgs/') !== -1) {
    event.preventDefault();
  }
});