我chrome.webRequest.onBeforeRequest
在后台脚本中使用它来侦听用户提出的所有请求。我的扩展名现在只是一个清单和这个bg脚本。
然后,我检查网址是否与正则表达式匹配:
chrome.webRequest.onBeforeRequest.addListener(
checkRedirect, {urls: ["<all_urls>"]}, ["blocking"]
);
function checkRedirect(details) {
var location = getLocation(details.url);
if(/some_regex/.test(details.url)) {
var redirect_url = 'http://some_redirect.com' + location.pathname;
chrome.tabs.update({url: redirect_url});
}
return {cancel: false};
}
function getLocation(href) {
var l = document.createElement('a');
l.href = href;
return l;
};
因此,如果用户进入页面或单击指向该页面的链接,我想将其重定向。上面的代码几乎可以正常工作;问题是当页面请求例如CSS时,这些CSS最终出现在用户屏幕上。
所以我想要的是只过滤对页面/点击的请求。
通过设置types
为将事件通知限制为顶级框架['main_frame']
(['main_frame', 'sub_frame']
如果您还希望包括框架,则使用此属性)。
尽管先前的建议可以解决您的问题,但我建议更进一步,并摆脱它chrome.tabs.update
。用于redirectUrl
将先前的请求替换为重定向到所需URL的地址。
如果您的URL模式匹配方法非常简单(可表示为匹配模式),则将过滤器合并到webRequest API过滤器的“ urls”键中。这将减少扩展程序对浏览器性能的影响。
chrome.webRequest.onBeforeRequest.addListener(function(details) {
var location = getLocation(details.url); // getLocation defined in question
var redirect_url = 'http://some_redirect.com' + location.pathname;
return { redirectUrl: redirect_url };
}, {
types: ['main_frame', 'sub_frame'],
urls: ['*://*/*some_pattern*']
}, ['blocking']);
注意:<all_urls>
如果您不准备处理非HTTP请求,请不要使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句