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:

        function(details) {
            if (/jsexample.js/.test(details.url))
                // setTimeout(requestScript(details), 0);
                return { 
                    redirectUrl: chrome.extension.getURL("novoScript.js")
        {urls: ['*://**.js']},

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.


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.



    "declarative_net_request" : {
            "rule_resources" : [{
              "id": "ruleset_1",
              "enabled": true,
              "path": "redirectRules.json"
     "permissions": [


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