Pepi
Pepi

Reputation: 171

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"]
);

Upvotes: 0

Views: 106

Answers (2)

Pepi
Pepi

Reputation: 171

Smile4ever's answer is correct but I found some other issues with my original code.

First - the 'timing' issue of my original content-script was a red herring. Although the original content script will write to the log of the page, it has no effect on loading resources. The same script, as a background script, will not write anything (that I have noticed) into the console log, but it will work.

Second - the background script needs more permissions than I had originally (more than are described in the mozilla.org link).

"permissions": [
  "http://*/*",
  "https://*/*",
  "webRequest",
  "webRequestBlocking" ]

The above permissions are adequate/excessive; you can also replace "http(s)://*/*" with the actual urls of the pages requesting the resource and the resource to be blocked.

Upvotes: 0

Smile4ever
Smile4ever

Reputation: 3704

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.

Upvotes: 1

Related Questions