识别XHR(AJAX)的反应,一边听HTTP响应在Firefox插件插件、边听、反应、AJAX

2023-09-10 18:07:03 作者:囚不得

我有一个简单的Firefox插件(插件-SDK)监听到http resposes和盖帽,如果响应的内容类型匹配一组内容类型。现在,观察者监听所有的答复时,我没有兴趣听的图像,JavaScript文件和AJAX(XHR)的反应。我能以某种方式过滤掉或至少找出应对属于一个XHR请求,这样我就不会浪费在处理响应的资源。

类似的事情,可以实现在Chrome浏览器扩展,其中details.type可以main_frame,图像,XHR等。

  HTT presponseObserver =
{
  注意:功能(主题,主题数据)
  {

    如果(主题==HTTP上审视反应)
    {
        VAR渠道= subject.QueryInterface(Ci.nsIHttpChannel);
        VAR的contentType;
        尝试 {
                的contentType = channel.getResponseHeader(Content-Type的');
                如果(/\b(?:xml|rss|javascript|vnd|json|html|text|image|ocsp|x-shockwave-flash)\b/.test(contentType))
                {
                    返回;
                }
            }
        赶上(错误){
                返回;
            }
}
}
 

解决方案

要求从 nsIXMLHtt prequest 接口 notificationCallbacks

VAR isXHR; 尝试{   VAR渠道= subject.QueryInterface(Ci.nsIHttpChannel);   VAR回调= channel.notificationCallbacks;   VAR XHR =回调? callbacks.getInterface(Ci.nsIXMLHtt prequest):空;   isXHR = !! XHR; } 赶上(E){   isXHR = FALSE; }

XHR 和 AJAX 的结合 API 测试

I have a simple firefox addon (addon-sdk) which listens to http resposes and blocks if content type of response matches a set of content types. Now, the observer listens to all the responses when I am not interested in listening to image, javascript files and ajax (XHR) responses. Can I somehow filter out or atleast find out that response belongs to an XHR request so that I don't waste resources on processing the response.

The similar thing can be achieved in chrome extensions where "details.type" can be main_frame, image, xhr etc.

httpResponseObserver =  
{  
  observe: function(subject, topic, data)  
  {  

    if (topic == "http-on-examine-response") 
    {
        var channel = subject.QueryInterface(Ci.nsIHttpChannel); 
        var contentType;
        try {
                contentType = channel.getResponseHeader('Content-Type');
                if (/\b(?:xml|rss|javascript|vnd|json|html|text|image|ocsp|x-shockwave-flash)\b/.test(contentType))
                {
                    return;
                } 
            } 
        catch(error) {
                return;
            }
}
}

解决方案

Request the nsIXMLHttpRequest interface from notificationCallbacks

var isXHR;

try{
  var channel = subject.QueryInterface(Ci.nsIHttpChannel);
  var callbacks = channel.notificationCallbacks;
  var xhr = callbacks ? callbacks.getInterface(Ci.nsIXMLHttpRequest) : null;
  isXHR = !!xhr;
}
catch(e){
  isXHR = false;
}