0

I followed the answer here: Intercept fetch() API requests and responses in JavaScript

inject.js

const { fetch: origFetch } = window;
window.fetch = async (...args) => {
  window.postMessage({ type: 'API_AJAX_CALL', payload: args }, '*');
  const response = await origFetch(...args);
  return response;
};

content_script.js

var headElement = (document.head || document.documentElement);
var injectJs = function (fileName) {
    var s = document.createElement('script');
    s.src = chrome.extension.getURL(fileName);
    headElement.insertBefore(s, headElement.firstElementChild);
};

// Register to receive the message from the injected script
window.addEventListener("message", function (event) {
    if (event.data.type && (event.data.type == "API_AJAX_CALL")) {
        console.log("CONTENT-SCRIPT-CONTEXT: Received the data " + event.data.payload[0]);
    }
}, false);

injectJs("inject.js");

manifest

  "content_scripts": [
        {
            "matches": ["*://*/*"],
            "js": ["content.js"],
            "run_at": "document_start",
            "all_frames": true
        }
    ],

but the patched api only captures some of the fetch calls (marked with green circles - injected content script). It even misses the fetch calls which happened after few of the fetch calls were captured.

enter image description here

surya
  • 991
  • 1
  • 12
  • 22

1 Answers1

1

There are limits to this sort of thing. Here's a probably-incomplete list of calls you can't intercept as shown:

  • Calls that started before your script was run
  • Calls where the code captured fetch to a local before your script was run (unlikely, but...):
    (() => { const myFetch = fetch; /*...code using `myFetch`...*/ })();
    
  • Calls made by service workers

You can only do what you can do. You might want to look at various webRequest events such as onBeforeRequest.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Thanks a lot for the insights. Service workers idea seems promising. I will explore that. – surya Nov 21 '22 at 10:18