HTTP请求观察器在无重启FF附加组件中

时间:2014-02-28 02:20:18

标签: javascript firefox firefox-addon firefox-addon-sdk

我正在开发一个无重启的FF插件,它将改变特定页面的HTTP请求(特别是用户代理)中的标头属性。

我一直在查看HTTP请求观察者文档https://developer.mozilla.org/en-US/docs/Setting_HTTP_request_headers#Observers,但这似乎在重新启动的SDK中不可用。我错过了什么吗?我是否有其他选项来更改来自特定页面的请求的用户代理?

谢谢!

1 个答案:

答案 0 :(得分:4)

复制粘贴,这将在访问任何Google网站时添加自定义标头:

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

也是一张纸条。因为您想要更改用户请求,请确保在httpChannel.setRequestHeader('MyCustomRequestHeader', 'hiiii', false);中将第三个参数设置为false,否则它会将预先存在的用户代理与您提供的新用户代理合并