How to redirect URLs using chrome.webRequest API?

后端 未结 1 1923
萌比男神i
萌比男神i 2021-01-07 03:59

background.js:

chrome.webRequest.onBeforeRequest.addListener(function (details) {
    console.log(details.url);
    wi         


        
1条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 04:29

    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.

    0 讨论(0)
提交回复
热议问题