I have a chrome extension that is meant to intercept response body data, manipulate it into useful statistics and then render these stats on the page.
The problem is that the request interceptor loads after the most important requests have already been sent/received so is unable to scrape them (see my attached images from the chrome network tab hopefully that’ll make things clearer).
Currently, my interceptor runs in a content.js script that is matched to the urls I'm interested in.
INTERCEPTOR.JS
listenerFn = (event) => {
console.log("Url:, ", event.target.responseURL);
// DO OTHER STUFF
}
(
() => {
var XHR = XMLHttpRequest.prototype;
var send = XHR.send;
XHR.send = function() {
this.addEventListener('load', listenerFn)
return send.apply(this, arguments);
};
}
)();
My manifest (V3) script looks like this...
MANIFEST.JSON
{
"manifest_version": 3,
.....
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["URL_OF_INTEREST.com/*"],
"js": ["interceptor.js"],
"run_at": "document_start"
}
],
"web_accessible_resources": [
{
"matches": ["<all_urls>"],
"resources": ["interceptor.js"]
}
],
"permissions": [
"scripting",
"activeTab",
"declarativeContent",
"storage",
"tabs"
],
"host_permissions": [
"*://*/*"
]
}
I feel like my options are either:
- Work out how to inject the interceptor script faster
- Delay page requests until the interceptor has been fully injected (impossible?)
- Try using chrome.WebRequest somehow
I don't know if any of these are possible. 1 - I don't think the interceptor can be injected sooner in the current setup (as i think I've done all I can with setting run_at). 2 - I dont even know if this can be done. 3 - I believe WebRequest doesn't give access to request bodys.
Someone mentioned to me that as the code is not related to page content it may be possible to have this code run in the background.js script. So maybe this is a good avenue to explore.
I've attached two images below showing the network tab from chrome dev tools.
In the first image (which shows only XHRs), the green arrow is the request that I need to scrape, the purple bracket covers requests that haven’t been intercepted and the yellow ones are requests that have. The colours are similar in the second image (which shows both XHRs and JS files), but this includes a blue arrow showing when the interceptor.js file has been run.
Any suggestions or guidance would be greatly appreciated. If anyone wants/requires any additional information just let me know,
Thanks!