Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

HTTP request observer in restartless FF add-on


I'm working on a restartless FF add-on that will change a header property in HTTP requests (specifically user agent) from a particular page.

I've been looking at the HTTP request observers documentation https://developer.mozilla.org/en-US/docs/Setting_HTTP_request_headers#Observers but this doesn't seem to be available in the restartless SDK. Am I missing something? Do I have another option for changing the user-agent of requests coming from a particular page?

Thanks!


Solution

  • copy paste, this will add a custom header when going to any google site:

    const {Cu, Ci} = require('chrome'); //im not sure about this line plz verify, im not an sdk guy but know a bit about it
    Cu.import('resource://gre/modules/Services.jsm');
    
    var httpRequestObserver =
    {
        observe: function(subject, topic, data)
        {
            var httpChannel, requestURL;
    
            if (topic == "http-on-modify-request") {
                httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
                requestURL = httpChannel.URI.spec;
    
                if (requestURL.indexOf('google.com') > -1) {
                    httpChannel.setRequestHeader('MyCustomRequestHeader', 'hiiii', false);
                }
    
                return;
            }
        }
    };
    
    Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
    //Services.obs.removeObserver(httpRequestObserver, "http-on-modify-request", false); //run this on shudown of your addon otherwise the observer stags registerd
    

    also a note. because you want to change user request make sure that third parameter is set to false in httpChannel.setRequestHeader('MyCustomRequestHeader', 'hiiii', false); otherwise it will merge the pre-existing user agent with the new one you supply