如何从Greasemonkey脚本拦截XMLHttpRequests?

时间:2009-03-10 10:59:07

标签: javascript ajax greasemonkey

我想使用Greasemonkey捕获AJAX请求的内容。

有人知道怎么做吗?

7 个答案:

答案 0 :(得分:52)

接受的答案几乎是正确的,但可以略微改进:

(function(open) {
    XMLHttpRequest.prototype.open = function() {
        this.addEventListener("readystatechange", function() {
            console.log(this.readyState);
        }, false);
        open.apply(this, arguments);
    };
})(XMLHttpRequest.prototype.open);

首选使用apply +参数而不是调用,因为那样你就不必明确地知道所有打开的参数可能会改变!

答案 1 :(得分:6)

如何修改XMLHttpRequest.prototype.open或发送带有替换的方法,这些替换设置自己的回调并调用原始方法?回调可以做它的事情然后调用回调指定的原始代码。

换句话说:

XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;

var myOpen = function(method, url, async, user, password) {
    //do whatever mucking around you want here, e.g.
    //changing the onload callback to your own version


    //call original
    this.realOpen (method, url, async, user, password);
}  


//ensure all XMLHttpRequests use our custom open method
XMLHttpRequest.prototype.open = myOpen ;

答案 2 :(得分:3)

在Chrome 55和Firefox 50.1.0中测试

在我的情况下,我想修改responseText,它在Firefox中是一个只读属性,所以我不得不包装整个XMLHttpRequest对象。我还没有实现整个API(特别是responseType),但它足以用于我拥有的所有库。

用法:

    XHRProxy.addInterceptor(function(method, url, responseText, status) {
        if (url.endsWith('.html') || url.endsWith('.htm')) {
            return "<!-- HTML! -->" + responseText;
        }
    });

代码:

(function(window) {

    var OriginalXHR = XMLHttpRequest;

    var XHRProxy = function() {
        this.xhr = new OriginalXHR();

        function delegate(prop) {
            Object.defineProperty(this, prop, {
                get: function() {
                    return this.xhr[prop];
                },
                set: function(value) {
                    this.xhr.timeout = value;
                }
            });
        }
        delegate.call(this, 'timeout');
        delegate.call(this, 'responseType');
        delegate.call(this, 'withCredentials');
        delegate.call(this, 'onerror');
        delegate.call(this, 'onabort');
        delegate.call(this, 'onloadstart');
        delegate.call(this, 'onloadend');
        delegate.call(this, 'onprogress');
    };
    XHRProxy.prototype.open = function(method, url, async, username, password) {
        var ctx = this;

        function applyInterceptors(src) {
            ctx.responseText = ctx.xhr.responseText;
            for (var i=0; i < XHRProxy.interceptors.length; i++) {
                var applied = XHRProxy.interceptors[i](method, url, ctx.responseText, ctx.xhr.status);
                if (applied !== undefined) {
                    ctx.responseText = applied;
                }
            }
        }
        function setProps() {
            ctx.readyState = ctx.xhr.readyState;
            ctx.responseText = ctx.xhr.responseText;
            ctx.responseURL = ctx.xhr.responseURL;
            ctx.responseXML = ctx.xhr.responseXML;
            ctx.status = ctx.xhr.status;
            ctx.statusText = ctx.xhr.statusText;
        }

        this.xhr.open(method, url, async, username, password);

        this.xhr.onload = function(evt) {
            if (ctx.onload) {
                setProps();

                if (ctx.xhr.readyState === 4) {
                     applyInterceptors();
                }
                return ctx.onload(evt);
            }
        };
        this.xhr.onreadystatechange = function (evt) {
            if (ctx.onreadystatechange) {
                setProps();

                if (ctx.xhr.readyState === 4) {
                     applyInterceptors();
                }
                return ctx.onreadystatechange(evt);
            }
        };
    };
    XHRProxy.prototype.addEventListener = function(event, fn) {
        return this.xhr.addEventListener(event, fn);
    };
    XHRProxy.prototype.send = function(data) {
        return this.xhr.send(data);
    };
    XHRProxy.prototype.abort = function() {
        return this.xhr.abort();
    };
    XHRProxy.prototype.getAllResponseHeaders = function() {
        return this.xhr.getAllResponseHeaders();
    };
    XHRProxy.prototype.getResponseHeader = function(header) {
        return this.xhr.getResponseHeader(header);
    };
    XHRProxy.prototype.setRequestHeader = function(header, value) {
        return this.xhr.setRequestHeader(header, value);
    };
    XHRProxy.prototype.overrideMimeType = function(mimetype) {
        return this.xhr.overrideMimeType(mimetype);
    };

    XHRProxy.interceptors = [];
    XHRProxy.addInterceptor = function(fn) {
        this.interceptors.push(fn);
    };

    window.XMLHttpRequest = XHRProxy;

})(window);

答案 3 :(得分:1)

您可以使用包装器替换文档中的unsafeWindow.XMLHttpRequest对象。一小段代码(未经测试):

var oldFunction = unsafeWindow.XMLHttpRequest;
unsafeWindow.XMLHttpRequest = function() {
  alert("Hijacked! XHR was constructed.");
  var xhr = oldFunction();
  return {
    open: function(method, url, async, user, password) {
      alert("Hijacked! xhr.open().");
      return xhr.open(method, url, async, user, password);
    }
    // TODO: include other xhr methods and properties
  };
};

但这有一个小问题:Greasemonkey脚本在页面加载后执行,因此页面可以在加载序列期间使用或存储原始XMLHttpRequest对象,因此在脚本执行之前发出请求,或者您的脚本不会跟踪真正的XMLHttpRequest对象。我没办法解决这个限制。

答案 4 :(得分:1)

在编写代理服务器时,我编写了一些用于拦截ajax调用的代码。它应该适用于大多数浏览器。

这是: https://github.com/creotiv/AJAX-calls-intercepter

答案 5 :(得分:0)

不确定是否可以使用greasemonkey执行此操作,但如果创建扩展,则可以使用观察者服务和http-on-examine-response观察器。

答案 6 :(得分:0)

基于提出的解决方案,我实现了“ xhr-extensions.ts”文件,该文件可用于打字稿解决方案。 使用方法:

  1. 将包含代码的文件添加到您的解决方案

  2. 这样导入

    import { XhrSubscription, subscribToXhr } from "your-path/xhr-extensions";
    
  3. 像这样订阅

    const subscription = subscribeToXhr(xhr => {
      if (xhr.status != 200) return;
      ... do something here.
    });
    
  4. 当您不再需要订阅时取消订阅

    subscription.unsubscribe();
    

“ xhr-extensions.ts”文件的内容

    export class XhrSubscription {

      constructor(
        private callback: (xhr: XMLHttpRequest) => void
      ) { }

      next(xhr: XMLHttpRequest): void {
        return this.callback(xhr);
      }

      unsubscribe(): void {
        subscriptions = subscriptions.filter(s => s != this);
      }
    }

    let subscriptions: XhrSubscription[] = [];

    export function subscribeToXhr(callback: (xhr: XMLHttpRequest) => void): XhrSubscription {
      const subscription = new XhrSubscription(callback);
      subscriptions.push(subscription);
      return subscription;
    }

    (function (open) {
      XMLHttpRequest.prototype.open = function () {
        this.addEventListener("readystatechange", () => {
          subscriptions.forEach(s => s.next(this));
        }, false);
        return open.apply(this, arguments);
      };
    })(XMLHttpRequest.prototype.open);