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

前端 未结 7 1973
面向向阳花
面向向阳花 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:28

    One very simple workaround is to change the property descriptor for responseText itself

    Object.defineProperty(wrapped, 'responseText', {
         writable: true
    });
    

    So, you can extend XMLHttpRequest like

    (function(proxied) {
        XMLHttpRequest = function() {
            //cannot use apply directly since we want a 'new' version
            var wrapped = new(Function.prototype.bind.apply(proxied, arguments));
    
            Object.defineProperty(wrapped, 'responseText', {
                writable: true
            });
    
            return wrapped;
        };
    })(XMLHttpRequest);
    

    Demo

提交回复
热议问题