Search code examples
javascriptfirefox-addonfirefox-addon-webextensionsweb-extension

webRequest.filterResponseData() always gives error "Invalid request ID"


I am trying to get the response body from an API call made by a website in a Firefox extension. I am trying to do that with the webRequest API. Every time I try to do so, the resulting filter gives me an error that says "Invalid request ID". I know the target web address and can narrow the reqFilter down enough to cause the entire listener function to only trigger once when I visit the site, but it doesn't like it when I create the filter with the request ID. It always has a status of "uninitialized." None of the filter events are even being triggered.

Here is the code from my background.js file:

const reqFilter = {
  urls: ["<target>"],
};

function listener(details) {
  let filter = browser.webRequest.filterResponseData(details.requestId);

  filter.onstart = (event) => {
    console.log("start called");
    console.log(event.data);
  };

  const data = [];
  filter.ondata = (event) => {
    console.log("data called");
    data.push(event.data);
    filter.disconnect();
  };

  filter.onerror = (event) => {
    console.log(filter.error);
  };

  console.log("at the end");
  return {};
}

browser.webRequest.onCompleted.addListener(listener, reqFilter);

console.log("extension started");

and my manifest.json file:

{
  "manifest_version": 2,
  "name": "<Name>",
  "version": "1.0",

  "description": "<Description>",

  "permissions": [
    "webRequest",
    "<all_urls>",
    "webRequestBlocking",
    "webRequestFilterResponse"
  ],

  "icons": {
    "48": "icons/logo48.png"
  },

  "background": {
    "scripts": ["background.js"]
  }
}

I tried:

  • requesting responses from any call from any website
    • this left me with the same invalid request id error
  • using different event listeners per the docs
    • all the events left me with the same results
  • making the listener function async and awaiting the filterResponseData
    • this changed nothing

I have:

  • looked through the docs for any potential errors in my code
  • looked through forums
  • looked at the example extensions mozilla give

Solution

  • As stated by @wOxxOm, adding 'blocking' to the list of extraInfoSpec seemed to solve this issue. The new line of code:

    browser.webRequest.onBeforeRequest.addListener(listener, reqFilter, ['blocking']);