Electron: prevent / cancel page navigation

2019-07-15 12:18发布

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

2条回答
Emotional °昔
2楼-- · 2019-07-15 12:58

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().

查看更多
何必那么认真
3楼-- · 2019-07-15 12:59

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();
  }
});
查看更多
登录 后发表回答