Search code examples
javascriptgoogle-chromewebrequest

Chrome extension - read web request body content


I have a chrome extension were I am trying to receive and save the contents of web requests. In this case I am listening for JavaScript files, and I want to save the actual js code received, but requestBody is always returning 'undefined'.

Am I missing something? Thanks

Manifest:

{
  "name": "Resource reader",
  "description": "resource reader test",
  "version": "1.0",
  "permissions": [
    "webRequest",
    "*://*/",
    "activeTab",
    "webRequestBlocking"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },
  "manifest_version": 2
}

background.js:

chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    var fileName = details.url;
    var extension = fileName.split('.').pop(); 
    if(extension === 'js'){
      console.log('received js file');
      console.log("url:"+details.url);
      console.log(details.requestBody);
    }
  },
  {urls: ["<all_urls>"], types:["script"]},
["requestBody"]);

output received:

received js file                                         background.js:6 
url:http://localhost:9095/hello.js                       background.js:7 
undefined                                                background.js:8 

Solution

  • You could use fetch() after you have detected the correct url you pretend to obtain.

    fetch(details.url)
          .then(response => response.text())
          .then(data => console.log(data));
    

    Now be careful not to enter an endless loop where you detect, fetch, detect, fetch.. the same file.