【问题标题】:Overriding XMLHttpRequest's send method覆盖 XMLHttpRequest 的发送方法
【发布时间】:2019-12-12 00:31:50
【问题描述】:
我正在尝试通过覆盖 XMLHttpRequest.send 函数记录(并稍后修改)XMLHttpRequest 发送到服务器的数据。
我的函数将数据正确记录到控制台,但是请求没有完成,因此浏览器会无限期地等待响应。
你知道代码有什么问题吗?
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;
【问题讨论】:
标签:
javascript
xmlhttprequest
【解决方案1】:
你忘了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);
【解决方案2】:
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;
【解决方案3】:
假设要更改的数据是一个 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;
}();