Search code examples
javascriptgoogle-chromehttp-redirectgoogle-chrome-extensionwebrequest

Chrome Extension OnBeforeRequest not triggering unless I click the poupup button


I'm building a chrome extension which needs to redirect a script of a certain page. My background.js includes:

    chrome.webRequest.onBeforeRequest.addListener(
        function(details) {
            if (/js\example.js/.test(details.url))
                // setTimeout(requestScript(details), 0);
                return { 
                    redirectUrl: chrome.extension.getURL("novoScript.js")
                }
        },
        {urls: ['*://*.example.com/*.js']},
        ["blocking"]
    );

The manifest.json includes:

"background": {
    "scripts": ["background.js"],
    "persistent": true
},

It works as expected, but the function only runs when I reload the page after having clicked the popup button. The first time I open the page in a new tab, it doesn't run. If I am in the page, and have clicked the popup button, it always works. If I haven't clicked, it doesn't matter how many times I reload, the redirect doesn't work.

I've tried erasing the whole content of popup.js, and it doesn't make a difference, so it's not because of any code there.

Also, I've checkedthe background.js file is not being ran again, so it seems that the listener is there, but it doesn't listen if I don't click the popup button. I've also added console.log to the listener function, and before I click the button it only logs calls to 'aobut:blank' url.

I'd like to allow the listener to work without clicking the popup, to avoid inconsistencies. Any help is appreciated.


Solution

  • I'm not sure about what was causing the problem. But an alternative approach that seems to be better overall, was pointed by @wOxxOm: declarativeNetRequest. With it, I applied a general rule for whenever the desired resource is requested.

    Implementation:

    manifest.json:

    {
        ...    
        "declarative_net_request" : {
                "rule_resources" : [{
                  "id": "ruleset_1",
                  "enabled": true,
                  "path": "redirectRules.json"
                }]
              },
         "permissions": [
              "declarativeNetRequest",
                "*://*.example.com/*"
            ],
          ...
    }
    

    redirectRules.json:

    [{
        "id": 1,
        "priority": 1,
        "action": {"type": "redirect", "redirect": {"extensionPath": "/novoScript.js" }},
        "condition" : {
            "urlFilter" : "js/app.*.js",
            "domains": ["example.com"],
            "resourceTypes" : ["script"]
        }
    }]