title: Using Fetch API to read HTTP response body from a chrome extension
body: <p>I'm trying to write a chrome extension that needs to intercept HTTP response data. I was looking at a similar extension but I couldn't understand the following part of the code:</p>
  <pre><code>(function() {
    'use strict';
    var oldXHR, stateChangeHandler, prop;
  
    oldXHR = window.XMLHttpRequest;
    stateChangeHandler = function (evt) {
  
      const constantMock = window.fetch;
      window.fetch = function() {
  
        return new Promise((resolve, reject) =&gt; {
            constantMock.apply(this, arguments)
                .then((response) =&gt; {
                    if (response.bodyUsed) {
                      resolve(response);
                    } else {
                      var mockResponse = response.clone().json();
  
                      mockResponse.then(function(result){
                        handleData(result);
                      });
                      resolve(response);
                    }
                })
                .catch((error) =&gt; {
                })
            });
      }
    };
  
    function newXHR() {
      var xhr = new oldXHR();
      xhr.addEventListener('readystatechange', stateChangeHandler);
      return xhr;
    }
  
    // Copy original states and toString
    for (prop in oldXHR)
      newXHR[prop] = oldXHR[prop];
  
    window.XMLHttpRequest = newXHR;
  })();
  </code></pre>
  <p>I was looking at Fetch API documentation online but in every example I found, there needed to be a specific url for it to work (ex: fetch(&quot;some url&quot;).then().catch()). How does the above fetch call work with no parameters? What is it fetching from?</p>
  <p>Separate questions - How does const constantMock = window.fetch work? How does apply() work?</p>
  <p>Also, is there a way to intercept JSON data from a web socket connection with a chrome extension as well? The pasted code only works with a long polling connection with the server.</p>