【发布时间】:2020-01-08 02:05:41
【问题描述】:
我有一个 chrome 扩展程序。
我想要的是:
当在页面(名为 A)中单击 <a> 标记时,我使用 chrome.webRequest.onBeforeRequest 阻止请求。
问题是:
我尝试了{redirectUrl: 'javascript:'} 和{cancel: true},但页面 A 仍然重定向。
如何防止 chrome 扩展中的重定向。
manifest.json:
{
"background": {
"page": "background.html"
},
"browser_action": {
"default_icon": "img/19.png",
"default_popup": "popup.html",
"default_title": "test"
},
"icons": {
"128": "img/128.png",
"48": "img/48.png"
},
"is_account_related": false,
"manifest_version": 2,
"minimum_chrome_version": "38.0.0.0",
"permissions": ["webRequest", "webRequestBlocking", "notifications", "tabs", "storage", "cookies", "http://*/*", "https://*/*", "*://*/*"],
"homepage_url": "xxxx",
"name": "test",
"description": "test",
"version": "10.3.6",
"content_security_policy": "script-src 'self' 'unsafe-eval' xxx 'unsafe-inline'; object-src 'self'",
"key": "xxx"
}
背景.html
chrome.webRequest.onBeforeRequest.addListener(
function (details) {
console.log('========start============');
console.log('block', details, details.url);
console.log('========end============');
// return { redirectUrl: 'javascript:' };
return { cancel: true };
},
{ urls: ["*://developer.mozilla.org/*"] },
['blocking']
);
在 background.html 中,日志是正确的。但页面仍在导航
=== 更新
我发现页面使用history API 进行导航。那么有什么办法可以防止history api,比如history.push,history.replace?
【问题讨论】:
-
1) 显示你的代码和manifest.json,它可能有错误。 2) 页面可能有自己的点击监听器,并通过操作
location对象导航到新 URL,您可以在 devtools(元素面板、事件监听器子面板)中检查该对象。后者可以被内容脚本使用标准事件方法(如 stopPropagation())阻止。 -
是的,我发现页面有自己的点击监听器。但我不喜欢将 javascript 注入页面。有没有其他方法可以阻止导航请求?
-
好吧,毕竟您的代码/清单中可能有错误。因为 webRequest 应该能够阻止任何页面启动的导航,无论其方法如何。
-
关于您的新编辑:历史导航不是真正的导航,因此要阻止它,您必须在页面上下文中覆盖 pushState (partial example)。
-
好的。得到它 。谢谢