3

background.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.

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?

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.

Makyen
  • 31,849
  • 12
  • 86
  • 121
Kaeus
  • 31
  • 1
  • 3
  • 2
    `does not work` ... what happens? do you get an error? the thing is, `background.js` does not *have* a `window` – Jaromanda X Mar 04 '17 at 08:00

1 Answers1

8

webRequest API provides redirection functionality.

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

"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:

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.

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.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • 1
    'webRequestBlocking' requires manifest version of 2 or lower. Is there an up-to-date solution? – Cardinal System Apr 19 '21 at 23:00
  • In ManifestV3 you should use declarativeNetRequest, more info in the [migration guide](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/). – wOxxOm Apr 20 '21 at 03:38