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
You can use the
will-navigate
event to stop navigation.You can also prevent requests (including redirects) using
webRequest.onBeforeRequest()
: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 towebRequest.onBeforeRequest()
.In my scenerio I've fixed it like below