How can I modify the XMLHttpRequest responsetext received by another function?

前端 未结 7 1961
面向向阳花
面向向阳花 2020-12-01 04:11

I am trying to modify the responseText received by a function that I cannot modify. This function creates a XMLHttpRequest that I can attach to, but I have been unable to \"

7条回答
  •  天命终不由人
    2020-12-01 04:39

    You can wrap the getter for responseText in the prototype with a new function and make the changes to the output there.

    Here is a simple example that appends the html comment to the response text:

    (function(http){
      var get = Object.getOwnPropertyDescriptor(
        http.prototype,
        'responseText'
      ).get;
    
      Object.defineProperty(
        http.prototype,
        "responseText",
        {
          get: function(){ return get.apply( this, arguments ) + ""; }
        }
      );
    })(self.XMLHttpRequest);
    

    The above function will change the response text for all requests.

    If you want to make the change to just one request then do not use the function above but just define the getter on the individual request instead:

    var req = new XMLHttpRequest();
    var get = Object.getOwnPropertyDescriptor(
      XMLHttpRequest.prototype,
      'responseText'
    ).get;
    Object.defineProperty(
      req,
      "responseText", {
        get: function() {
          return get.apply(this, arguments) + "";
        }
      }
    );
    var url = '/';
    req.open('GET', url);
    req.addEventListener(
      "load",
       function(){
         console.log(req.responseText);
       }
    );
    req.send();
    

提交回复
热议问题