电子:防止/取消页面导航 [英] Electron: prevent / cancel page navigation

查看:155
本文介绍了电子:防止/取消页面导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正有没有阻止或取消电子中页面导航的方法?

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.

类似地,我也想对事件"did-get-redirect-request"执行相同的操作,以防止发生某些重定向.

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

非常感谢

推荐答案

您可以使用

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

您还可以使用 webRequest.onBeforeRequest()阻止请求(包括重定向) :

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({})
})

如果要阻止所有重定向,可以将侦听器添加到 webRequest.onBeforeRedirect() 并将重定向URL添加到阻止的URL列表中,然后您可以检入添加到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 to webRequest.onBeforeRequest().

这篇关于电子:防止/取消页面导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆