javascript 覆盖 XMLHttpRequest 的发送方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9700904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overriding XMLHttpRequest's send method
提问by user1268760
I'm trying to log (and later modify) the data XMLHttpRequest
sends to a server by overriding XMLHttpRequest.send
function.
我正在尝试XMLHttpRequest
通过覆盖XMLHttpRequest.send
函数记录(并稍后修改)发送到服务器的数据。
My function logs the data correctly to the console, however the request doesn't finish, therefore the browser keeps waiting for the response indefinitely.
我的函数将数据正确记录到控制台,但是请求没有完成,因此浏览器无限期地等待响应。
Any ideas what's wrong with the code?
任何想法代码有什么问题?
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
回答by ZER0
You have forgot this
:
你忘记了this
:
this.realSend(vData);
However, you don't need to add a new method to the prototype:
但是,您不需要向原型添加新方法:
var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data) {
send.call(this, data);
}
Using closure, you can also avoid rogue variables:
使用闭包,您还可以避免流氓变量:
!function(send){
XMLHttpRequest.prototype.send = function (data) {
send.call(this, data);
}
}(XMLHttpRequest.prototype.send);
回答by xdazz
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;
回答by Matteo Guarnerio
Assuming the data to change is a JSON string you can write an interceptor like this one:
假设要更改的数据是一个 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;
}();