title: Chrome extension: intercept HTTP Response
body: <p>I saw many pages talking about how to interecet HTTP Response from a site. I'm trying this: <a href="https://stackoverflow.com/questions/18534771/chrome-extension-how-to-get-http-response-body">Chrome Extension - How to get HTTP Response Body?</a>
  There are no execuble programs... this is my code:</p>
  
  <p>manifest.json:</p>
  
  <pre><code>{
    "manifest_version": 2,
  
    "name": "Extension Name",
    "description": "Some Desc.",
    "version": "1.1",
  
    "browser_action": {
      "default_icon": "icon.png",
      "default_popup": "index.html"
    },
    "permissions": [
      "activeTab",
      "storage",
      "tabs",
      "https://*.google.com/"
    ],
    "content_scripts": [
      {
        "matches": ["https://*.google.com/"],
        "run_at": "document_start",
        "js": ["contentscript.js", "inject.js"]
      }
    ],
    "web_accessible_resources": ["injected.js"]
  }
  </code></pre>
  
  <p>index.html:</p>
  
  <pre><code>&lt;html&gt;
  
      &lt;head&gt;
          &lt;script src="contentscript.js"&gt;&lt;/script&gt;
      &lt;/head&gt;
  
      &lt;body&gt;
              &lt;p&gt;HTTP INTERCEPTOR&lt;/p&gt;
      &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  
  <p>injected.js:</p>
  
  <pre><code>(function(xhr) {
      console.log('injeced file');
  
      var XHR = XMLHttpRequest.prototype;
  
      var open = XHR.open;
      var send = XHR.send;
      var setRequestHeader = XHR.setRequestHeader;
  
      XHR.open = function(method, url) {
          this._method = method;
          this._url = url;
          this._requestHeaders = {};
          this._startTime = (new Date()).toISOString();
  
          return open.apply(this, arguments);
      };
  
      XHR.setRequestHeader = function(header, value) {
          this._requestHeaders[header] = value;
          return setRequestHeader.apply(this, arguments);
      };
  
      XHR.send = function(postData) {
  
          this.addEventListener('load', function() {
              var endTime = (new Date()).toISOString();
  
              var myUrl = this._url ? this._url.toLowerCase() : this._url;
              if(myUrl) {
  
                  if (postData) {
                      if (typeof postData === 'string') {
                          try {
                              // here you get the REQUEST HEADERS, in JSON format, so you can also use JSON.parse
                              this._requestHeaders = postData;    
                          } catch(err) {
                              console.log('Request Header JSON decode failed, transfer_encoding field could be base64');
                              console.log(err);
                          }
                      } else if (typeof postData === 'object' || typeof postData === 'array' || typeof postData === 'number' || typeof postData === 'boolean') {
                              // do something if you need
                      }
                  }
  
                  // here you get the RESPONSE HEADERS
                  var responseHeaders = this.getAllResponseHeaders();
  
                  if ( this.responseType != 'blob' &amp;&amp; this.responseText) {
                      // responseText is string or null
                      try {
  
                          // here you get RESPONSE TEXT (BODY), in JSON format, so you can use JSON.parse
                          var arr = this.responseText;
  
                          // printing url, request headers, response headers, response body, to console
  
                          console.log(this._url);
                          console.log(JSON.parse(this._requestHeaders));
                          console.log(responseHeaders);
                          console.log(JSON.parse(arr));                        
  
                      } catch(err) {
                          console.log("Error in responseType try catch");
                          console.log(err);
                      }
                  }
  
              }
          });
  
          return send.apply(this, arguments);
      };
  
  })(XMLHttpRequest);
  </code></pre>
  
  <p>inject.js I set a timeout so I can enable the debugger:</p>
  
  <pre><code>/**
   * code in inject.js
   * added "web_accessible_resources": ["injected.js"] to manifest.json
   */
  
  setTimeout(function() {
      var s = document.createElement('script');
      s.src = chrome.extension.getURL('injected.js');
      s.onload = function() {
          this.remove();
          console.log('remove');
      };
      (document.head || document.documentElement).appendChild(s);
  }, 10000);
  </code></pre>
  
  <p>Why the code is not inject in <a href="https://www.google.com/" rel="nofollow noreferrer">https://www.google.com/</a>? Inspecting the DOM I don't see the code... the code runs and XHR is setrtes but the method open, setRequestHeader and send are never colled.</p>