如何使用chrome.webRequest API重定向URL? [英] How to redirect URLs using chrome.webRequest API?

查看:522
本文介绍了如何使用chrome.webRequest API重定向URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

background.js:

background.js:

chrome.webRequest.onBeforeRequest.addListener(function (details) {
    console.log(details.url);
    window.location.href = 'http://time.com/';
}, {urls: ['<all_urls>']}, []);

当我访问网站时,它会在控制台中显示所有请求,但不会将网站重定向到time.com.

It shows all requests in the console when I visit a web site, but it doesn't redirect the site to time.com.

其他信息:

我在后台控制台上出现错误:

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)

然后...在这种情况下,是否可以通过time.com的console.log查看请求?

then... is there a way to see requests with console.log from time.com in this case?

我喜欢查看请求,不需要在Chrome窗口上重定向. 我需要的只是请求在后台控制台中查看.

I like to see request and don't need to redirect on Chrome window. What I need is only request to see in background console.

推荐答案

webRequest API 提供重定向功能.

在manifest.json中添加webRequestBlockingwebRequest和主机权限:

Add webRequestBlocking, webRequest, and host permissions in manifest.json:

"permissions" : [
    "webRequest",
    "webRequestBlocking",
    "http://www.example.com/*" /* or <all_urls> */
],
"background": {
    "scripts": ["background.js"]
}

blocking侦听器中拦截要重定向的URL上的页面本身(main_frame)和iframe(sub_frame)的请求(这些应在上面显示的权限"中声明):

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:

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'
]);

要查看后台控制台,请在chrome://扩展页面上将其打开.

To view the background console, open it on chrome://extensions page.

此外,请务必阅读文档中的扩展架构文章:后台页面是一个完全独立的页面,与网页无关,具有自己的上下文和自己的URL,例如chrome-extension://blablabla/background.html,无法导航到另一个URL.

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.

这篇关于如何使用chrome.webRequest API重定向URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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