使用jQuery捕获XHR?

时间:2011-11-13 22:12:33

标签: jquery phantomjs

我正在使用带有jQuery的PhantomJS,我想知道是否有可能捕获XMLHttpRequest,因为它已传递给浏览器,而不是自己启动POST / GET。

3 个答案:

答案 0 :(得分:8)

有一些简单的jQuery函数可以让你在发送之前修改AJAX请求,但它们只针对jQuery发起的AJAX请求。要捕获页面上的所有AJAX请求,请使用以下基本的JS-only方式:

(function(open){
    XMLHttpRequest.prototype.open = function(method, url, async, username, password) {
        // modify the variables here as needed or use 'this` keyword to change the XHR object or add event listeners to it
        open.call(this, method, url, async, username, password);
    };
})(XMLHttpRequest.prototype.open);

您还可以重写XHR send()函数:

(function(send){
    XMLHttpRequest.prototype.send = function(body) {
       // your code
       send.call(this, body);
    };
})(XMLHttpRequest.prototype.send);

基本上,此代码必须是在您的页面上运行的第一个代码。所有后续的XHR请求都将通过重写的函数,允许您更改任何参数等。

注意:如果您希望定位某些版本的IE,则需要为IE用于AJAX的ActiveXObject实现类似的代码。

答案 1 :(得分:1)

ajaxPrefilter听起来不错,但从未使用过它。这会在转到服务器之前过滤请求。然后,您可以使用pipe在请求返回时修改您想要的内容:

$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    jqXHR.pipe(function(data){
        //modify the data the way you want
    })
});

答案 2 :(得分:0)

为页面发出的所有XHR / AJAX请求调用Phantom的onResourceReceived回调。两次,实际上,一次是stage =“start”,一次是stage =“end”。它不会提供内容,但它会捕获URL。