Electron: prevent / cancel page navigation

冷暖自知 提交于 2019-12-12 19:50: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


回答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();
  }
});


来源:https://stackoverflow.com/questions/41068295/electron-prevent-cancel-page-navigation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!