background.js:
chrome.webRequest.onBeforeRequest.addListener(function (details) {
console.log(details.url);
wi
webRequest API provides redirection functionality.
Add webRequestBlocking
, webRequest
, and host permissions in manifest.json:
"permissions" : [
"webRequest",
"webRequestBlocking",
"http://www.example.com/*" /* or */
],
"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
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.