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

前端 未结 7 1975
面向向阳花
面向向阳花 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-01 04:17

    I needed to intercept and modify a request response so I came up with a little bit of code. I also found that some websites like to use response as well as the responseText which is why my code modifies both.

    The Code

    var open_prototype = XMLHttpRequest.prototype.open,
    intercept_response = function(urlpattern, callback) {
       XMLHttpRequest.prototype.open = function() {
          arguments['1'].match(urlpattern) && this.addEventListener('readystatechange', function(event) {
             if ( this.readyState === 4 ) {
                var response = callback(event.target.responseText);
                Object.defineProperty(this, 'response',     {writable: true});
                Object.defineProperty(this, 'responseText', {writable: true});
                this.response = this.responseText = response;
             }
          });
          return open_prototype.apply(this, arguments);
       };
    };
    

    the first param of the intercept_response function is a regular expression to match the request url and the second param is the function to be used on the response to modify it.

    Example Of Usage

    intercept_response(/fruit\.json/i, function(response) {
       var new_response = response.replace('banana', 'apple');
       return new_response;
    });
    

提交回复
热议问题