0

I'm trying to have a background script listen to responses, examine the data, and (once I've got this working), call make another request. I'm stuck on the first part, simply listening to the responses. I don't want to filter or change the responses, but it looks like webRequest.StreamFilter is the only way to monitor responses.

I have completed the 'your first extension' on the MDN site, read the relevant docs on background scripts, and looked at examples on mdn/webextensions-examples.

Here's my manifest.json and background script:

{
  "manifest_version": 2,
  "name": "MyResponseListener",
  "version": "1.0",

  "description": "Listens to responses.",

  "icons": {
    "48": "icons/border-48.png"
  },

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

  "permissions" : [
    "webRequest", "webRequestBlocking", "*://*.siteToListenTo.com/*"
  ]
}

Here's the script:

console.log("extension enabled")

function listener(details) {
    let filter = browser.webRequest.filterResponseData(details.requestId);
    
    filter.onstart = event => {
        console.log("filter started");
    }

    filter.ondata = event => {
        console.log("filter data : " + event.data);
    }

    filter.onstop = event => {
        console.log("filter finished");
    }
  
    return {};
  }
  
  // have also tried this with types: ["main_frame"] as seen in some examples, but no difference
  browser.webRequest.onCompleted.addListener(
    listener,
    {urls: ["https://siteToListenTo.com/*"]},
    ["blocking"]
  );

It's not even printing the 'extension enabled' to the console. Not sure if I'm supposed to be looking at Browser console or Web Console in the developer tools.

user26270
  • 6,904
  • 13
  • 62
  • 94
  • If you're not even seeing the "extension enabled" message then you're most definitely looking at the wrong console. After you load the addon you will see it listed alongside the other addons in the "this-firefox" page. You will find an "Inspect" button right next to it, if you click this button it will take you to the console that should be logging the "extension enabled" message. Also, if you're not modifying the responses then you don't need to pass the "blocking" option, you can't even pass the "blocking" option on an onCompleted event, "responseHeaders" is the only available option here. – GoPotato Feb 23 '21 at 04:26
  • On a second thought, since you need to examine the response body, you can listen to the onBeforeRequest event with the "blocking" option. This will work for your use case I believe, this way you can access the response body through the filterResponseBody method you're using in your listener. – GoPotato Feb 23 '21 at 04:45
  • @GoPotato thanks; looks like it loaded and I could see more logs, but then it looked like the page is blocking my script! It's Discord, so that actually make sense; some kind of Content Security Policy – user26270 Feb 23 '21 at 23:17

0 Answers0