我正在尝试通过覆盖XMLHttpRequest的send函数来记录(以及稍后修改)XMLHttpRequest发送到服务器的数据。我的函数将数据正确记录到控制台,但请求没有完成,因此浏览器会无限期地等待响应。任何想法代码有什么问题?
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
答案 0 :(得分:19)
您已忘记this
:
this.realSend(vData);
但是,您不需要为原型添加新方法:
var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data) {
send.call(this, data);
}
使用闭包,您还可以避免恶意变量:
!function(send){
XMLHttpRequest.prototype.send = function (data) {
send.call(this, data);
}
}(XMLHttpRequest.prototype.send);
答案 1 :(得分:17)
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
// here "this" points to the XMLHttpRequest Object.
var newSend = function(vData) { console.log("data: " + vData); this.realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
答案 2 :(得分:0)
假设要更改的数据是一个JSON字符串,您可以编写这样的拦截器:
// Closure to contain variables and ! to avoid possible concatenation issues with other codes.
!function(){
XMLHttpRequest.prototype._original_send = XMLHttpRequest.prototype.send;
let interceptor_send = function(data){
try {
// Adding data to the JSON string,
// translating in JSON object to validate it's content and add an attribute.
obj = JSON.parse(data);
obj._custom_added_data = 'Your data';
let new_data = JSON.stringify(obj);
this._original_send(new_data);
}
catch(err) {
// In case the payload was not a JSON string,
// do not add anything and send the original payload.
this._original_send(data);
}
};
XMLHttpRequest.prototype.send = interceptor_send;
}();