2017-03-04 95 views
0

background.js:如何使用chrome.webRequest API重定向URL?

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

它顯示控制檯中的所有請求,當我訪問一個網站,但它不會重定向網站time.com。

附加信息:

我在這裏背景控制檯錯誤:

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) 

然後...有沒有辦法看到的console.log從time.com在這種情況下請求?

我喜歡看到請求,並且不需要在Chrome窗口上重定向。 我需要的只是請求在後臺控制檯中看到。

+1

'不起作用... ...會發生什麼?你有錯誤嗎?事情是,'background.js'不具有'窗口' –

回答

3

webRequest API提供重定向功能。

添加webRequestBlockingwebRequest,和主機權限的manifest.json:

"permissions" : [ 
    "webRequest", 
    "webRequestBlocking", 
    "http://www.example.com/*" /* or <all_urls> */ 
] 

的頁面本身(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' 
]); 

要查看背景控制檯,open it on chrome://extensions page

此外,請務必閱讀文檔中的extensions architecture文章:背景頁面是一個完全獨立的頁面,與網頁無關,具有自己的上下文和自己的URL,如chrome-extension:// blablabla /無法導航到另一個網址的background.html。