重写XMLHttpRequest's发送方法

Overriding XMLHttpRequest's send method

本文关键字:方法 XMLHttpRequest 重写      更新时间:2023-09-26

我正试图通过重写XMLHttpRequest.send函数来记录(稍后修改)XMLHttpRequest发送到服务器的数据。

我的函数将数据正确地记录到控制台,但请求没有完成,因此浏览器会无限期地等待响应。

你知道代码出了什么问题吗?

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) { console.log("data: " + vData); realSend(vData); };
XMLHttpRequest.prototype.send = newSend;

您忘记了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);
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;

假设要更改的数据是一个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;
}();