Search code examples
requestfirefox-addonmozillafirefox-addon-webextensions

Mozilla addon loading too late to block a resource


I'm trying to cancel requests from studio.code.org to www.google.com/jsapi to help page loads go faster. In my locale, google is blocked, but the browser waits for 75 seconds before giving up. I'd like to prevent the delay by blocking the request (and the page seems to work fine without jsapi).

I followed the example from https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest, installed the addon. I included a console.log statement to see that my code is called, but it only shows up after the browser waits another 75 seconds trying to load the resource that I hoped to block.

I'm open to other approaches if this isn't going to work.

manifest.json:

{
  "manifest_version": 2,
  "name": "cancel-google",
  "version": "1.0",

  "permissions": [
    "webRequest",
    "webRequestBlocking"
  ],

  "content_scripts": [
    {
      "matches": ["https://studio.code.org/*"],
      "js": ["cancel-google.js"]     
    } 
  ]
}

cancel-google.js:

// match pattern for the URLs to block
var pattern = "*www.google.com/jsapi";
console.log("cancelator script loaded");

// cancel function returns an object
// which contains a property `cancel` set to `true`
function cancel(requestDetails) {
  console.log("Cancelling: " + requestDetails.url);
  return {cancel: true};
}

// add the listener,
// passing the filter argument and "blocking"
browser.webRequest.onBeforeRequest.addListener(
  cancel,
  {urls: [pattern]},
  ["blocking"]
);

Solution

  • cancel-google.js should be loaded as a background script, which is true for most of the WebExtension APIs.

    {
        "name": "Your Addon",
        "manifest_version": 2,
        "background": {
            "scripts": ["cancel-google.js"]
        }
    }
    

    Then it should work.