javascriptasynchronousgoogle-chrome-extensionxpcomfirefox-addon-webextensions

How to block resources based on their content before they are loaded in Webextensions?


I want to block resources (like JavaScript- or CSS-files), before they are fully loaded. The condition, if resources are blocked, depends on their content. Actually, there is no solution for doing this, or?

What i know: Webextensions are similar to Chrome extensions, so they have also the webRequest.onBeforeRequest listener. The listener allows to block files:

function cancel(requestDetails) {
  console.log("Canceling: " + requestDetails.url);
  return {cancel: true};
}

chrome.webRequest.onBeforeRequest.addListener(
  cancel,
  {urls: ["<all_urls>"], types: ["script"]},
  ["blocking"]
);

Until this point, everything is fine. There should also be the requestBody option, so i can make my decision based on the content of the file. But Mozilla Doc says:

  1. Firefox does not support the "requestBody" option.

Oh, bad story, not cool. So i need an asynchronous XHR request, to get the URLs data:

function cancel(requestDetails) {
   return {cancel: getUrlContent(requestDetails.url, function(result) {
      if(condition) { console.log(true); } else { console.log(false); }
   })};
}

// asynchron XHR request
function getUrlContent(url, callback) { [...] }

=> This doesn't work. the return {cancel: X}; accepts normal functions, like return {cancel: doSth()};, but no asynchron callbacks. I have no option to "return" the result to the cancel JSON.

In other stackoverflow questions, i read about nsIContentPolicy, which is part of
XPCOM. I didn't found a hint, example or description, how i can use this in the Firefox Webextension environment. Is this possible? And if yes, how?

If both things are not possible, how i can do such an extension? Do i have to use the deprecated XPCOM without Webextension?


Solution

  • It looks like requestBody will land in an upcoming version of Firefox (currently appears to be 50): bugzilla.mozilla.org/show_bug.cgi?id=1201979. Which is to say, you can probably test in Beta now, since 49 was released this week.