custom XMLHttpRequest.prototype.open

北战南征 提交于 2019-12-30 07:04:06

问题


var open = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
    this.addEventListener("readystatechange", function(event) {  
    if(this.readyState == 4){
       var self = this;
       var response = {
         method: method,
         uri: uri,
         responseText: self.responseText
      };
      console.log(response);  
    } else {
        console.log(this.readyState);
    }
    }, false);
  open.call(this, method, uri, async, user, pass);
};

I am trying to listen for XHR before they are being sent. Something similar to jQuery's beforeSend in the $.ajax method.

My goal is to listen for all XHR's before they are being sent. I suppose the closest thing would be to check above if this.readyState === 1?

Would the code above cause any ajax libraries like jQuery to malfunction because I use prototype on XMLHttpRequest?


回答1:


I am trying to listen for XHR before they are being sent.

Then try to spoof the send() method, not the open() one.

Would the code above cause any ajax libraries like jQuery to malfunction because I use prototype on XMLHttpRequest?

No, not really. Only,

  • it won't work where those libs choose not to use XMLHttpRequest (particularly IE)
  • …and even fail if the browser does not support the XMLHttpRequest object (or does not support accessing or modifying its prototype)
  • libs might be able to work around your spoof by dereferencing the functions before you can (though I don't know any common lib that does)
  • Your code calls the native method with a fixed number of arguments, not sure if that affects anything, and it does not re-return the result (even if we know it's undefined). To be 100% sure, use return open.apply(this, arguments);.


来源:https://stackoverflow.com/questions/15768369/custom-xmlhttprequest-prototype-open

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!