Search code examples
javascriptgoogle-chrome-extensionfirefox-addon

Firefox browser.webRequest.onBeforeSendHeaders. No Clue why nothing happens


So, this is about extensions for Browsers and trying to intercept Headers and interact with them before a GET request gets made. I'm just trying some new things out, and wanted to play around with the webRequest.onBefoerSendHeaders, however it doesn't seem to do anything.

I just want to log something to the console if a certain header exists. Here is my code:

var requestFilter = {
    urls: ["random Site"]
}

var extraInfoSpec = ['requestHeaders', 'blocking']

handler = function(details) {

    var headers = details.requestHeaders;

    for (var i = 0, l = headers.length; i < l; ++i) {
        if (headers[i].name == 'User-Agent') {
            console.log("It works!")
            break;
        }
    }

};

browser.webRequest.onBeforeSendHeaders.addListener(handler, requestFilter, extraInfoSpec);

Here is the manifest:

{

"manifest_version": 2,
"name": "test",
"version": "1.0",

"description": "test",

"icons": {
  "48": "empty"
},

"content_scripts": [
  {
    "matches": ["*://random Site/*"],
    "js": ["header.js"]
  }
],

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

I do know there are some unused permissions and the speficied URL etc. does not exist.

Does somebody know why it does nothing? It is supossed to run in Firefox and Chrom.


Solution

  • Based on your manifest file it looks like you are attempting to use the webRequest API with a content script. However browser.webRequest is not available to content scripts and it will need to be converted to a background script in order to work.

    I would recommend removing the content script configuration and configuring the code to run as a background script.

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