[英]How to redirect URLs using chrome.webRequest API?
background.js:背景.js:
chrome.webRequest.onBeforeRequest.addListener(function (details) {
console.log(details.url);
window.location.href = 'http://time.com/';
}, {urls: ['<all_urls>']}, []);
It shows all requests in the console when I visit a web site, but it doesn't redirect the site to time.com.当我访问一个网站时,它会在控制台中显示所有请求,但它不会将该站点重定向到 time.com。
Additional Information:附加信息:
I got error on background console here:我在后台控制台上遇到错误:
Error in event handler for webRequest.onHeadersReceived/1: ReferenceError: url is not defined at chrome.webRequest.onHeadersReceived.addListener.urls (chrome-extension://hkiajgmcjicgampfdeiiacbojlmdokob/background.js:5:8)
then... is there a way to see requests with console.log from time.com in this case?那么...在这种情况下,有没有办法查看来自 time.com 的带有 console.log 的请求?
I like to see request and don't need to redirect on Chrome window.我喜欢看到请求并且不需要在 Chrome 窗口上重定向。 What I need is only request to see in background console.我需要的只是请求在后台控制台中查看。
webRequest API provides redirection functionality. webRequest API提供重定向功能。
Add webRequestBlocking
, webRequest
, and host permissions in manifest.json:在 manifest.json 中添加webRequestBlocking
、 webRequest
和主机权限:
"permissions" : [
"webRequest",
"webRequestBlocking",
"http://www.example.com/*" /* or <all_urls> */
],
"background": {
"scripts": ["background.js"]
}
Intercept requests for the page itself ( main_frame
) and iframes ( sub_frame
) on the URLs you want to redirect (those should be declared in "permissions" shown above) in a blocking
listener:对于页面本身(拦截请求main_frame
)和iframe中( sub_frame
)您要重定向的(那些应该“权限”如上图所示声明)的URL blocking
监听器:
chrome.webRequest.onBeforeRequest.addListener(function(details) {
console.log(details.url);
if (!details.url.startsWith('http://time.com/')) {
return {redirectUrl: 'http://time.com'};
}
}, {
urls: ['http://www.example.com/*'], // or <all_urls>
types: ['main_frame', 'sub_frame'],
}, [
'blocking'
]);
To view the background console, open it on chrome://extensions page .要查看后台控制台,请在 chrome://extensions 页面上打开它。
Also, make sure to read the extensions architecture article in the documentation: the background page is a totally separate page, not related to the web page, with its own context and its own URL like chrome-extension://blablabla/background.html which cannot be navigated to another URL.另外,请务必阅读文档中的扩展架构文章:背景页面是一个完全独立的页面,与网页无关,具有自己的上下文和自己的 URL,如 chrome-extension://blablabla/background.html无法导航到另一个 URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.