我正在使用PhantomJS和jQuery,我想知道是否有可能捕获XMLHttpRequest,因为它传递给浏览器,而不是自己启动POST/GET.
有一些简单的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);
Run Code Online (Sandbox Code Playgroud)
您还可以重写XHR send()函数:
(function(send){
XMLHttpRequest.prototype.send = function(body) {
// your code
send.call(this, body);
};
})(XMLHttpRequest.prototype.send);
Run Code Online (Sandbox Code Playgroud)
基本上,此代码必须是在您的页面上运行的第一个代码.所有后续的XHR请求都将通过重写的函数,允许您更改任何参数等.
注意:如果您希望定位某些版本的IE,则需要为IE用于AJAX的ActiveXObject实现类似的代码.