How to check if HTTP requests are open in browser?

后端 未结 4 712
一生所求
一生所求 2020-12-09 04:51

Is there an easy way to detect if an XMLHttpRequest is active in the browser window? Or how many are active? ie. Is there a way to detect if there are any AJAX

相关标签:
4条回答
  • 2020-12-09 05:00

    There is not a way to detect an open connection from JS unless you write a wrapper for XmlHttpRequest (or monkey patch it) that keeps track of opened connections.

    Here's kidcapital's monkey patch, not sure if it's perfect, but it's a good start

      (function() {
        var oldOpen = XMLHttpRequest.prototype.open;
        window.openHTTPs = 0;
        XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
          window.openHTTPs++;
          this.addEventListener("readystatechange", function() {
              if(this.readyState == 4) {
                window.openHTTPs--;
              }
            }, false);
          oldOpen.call(this, method, url, async, user, pass);
        }
      })();
    
    0 讨论(0)
  • 2020-12-09 05:05

    By using jQuery, you can keep track if there are open requests with the global event handlers: .ajaxStart() and .ajaxComplete()

    A global variable set on ajaxStart and reset on ajaxComplete should do the job.

    0 讨论(0)
  • 2020-12-09 05:08

    You can use FireBug for that.

    enter image description here

    0 讨论(0)
  • 2020-12-09 05:08

    I tried @juan-mendes's solution and got an error: ERROR Error Code: undefined Message: Failed to set the 'responseType' property on 'XMLHttpRequest': The response type cannot be changed for synchronous requests made from a document. in my Angular application. The cause is the async parameter which is supposed to be true by default, but when the argument is missing, this patch passes undefined which translates to false. The code with this small change works for me:

    (function() {
            var oldOpen = XMLHttpRequest.prototype.open;
            window.openHTTPs = 0;
            XMLHttpRequest.prototype.open = function(method, url, async = true, user = null, pass = null) {
                window.openHTTPs++;
                this.addEventListener("readystatechange", function() {
                    if(this.readyState == 4) window.openHTTPs--;
                }, false);
                oldOpen.call(this, method, url, async, user, pass);
            }
        })()
    
    0 讨论(0)
提交回复
热议问题