As I strive to intercept all XMLHttpRequests using my extension, I have managed to achieve partial success with my current implementation. However, it is not working as intended. While I am aware of webRequests, they do not allow me to modify the post/get data like in the code snippet below. The following code can be executed:
Inject.js
(function(){
console.log("Injected Send")
var proxiedSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
console.log(this, arguments );
return proxiedSend.apply(this, [].slice.call(arguments));
}
})();
(function(){
console.log("Injected Open")
var proxiedOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
console.log(this, arguments );
return proxiedOpen.apply(this, [].slice.call(arguments));
};
})();
When this piece of code is included in my content script, it will display "Injected Send" and "Injected Open". However, upon testing, it exhibits erratic behavior.
If you were to run the code snippet below in the console, you would observe that it successfully intercepts requests made but fails to work on XMLHttpRequests initiated on the page (both new and old objects). It only intercepts XMLHttpReuests initiated through the console. An example of this is provided here: https://www.w3schools.com/code/tryit.asp?filename=GBUKE1JS7IFL. Although it works within the webpage, replicating the same behavior by injecting it via an extension seems challenging.
(function(){
console.log("Injected Send")
var proxiedSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
console.log(this, arguments );
return proxiedSend.apply(this, [].slice.call(arguments));
}
})();
(function(){
console.log("Injected Open")
var proxiedOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
console.log(this, arguments );
return proxiedOpen.apply(this, [].slice.call(arguments));
};
})();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("success")
}
};
xhttp.open("GET", "/", true);
xhttp.send();
This perplexing issue is hindering the functionality of my Inject.js.
manifest.json
{
"name": "test",
"version": "0.0.1",
"manifest_version": 2,
"description": "testing xmlhttprequests",
"homepage_url": "http://example.com",
"icons": {
"16": "icons/icon16.png",
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"default_locale": "en",
"background": {
"scripts": [
"src/bg/background.js"
],
"persistent": true
},
"page_action": {
"default_icon": "icons/icon19.png",
"default_title": "page action demo",
"default_popup": "src/page_action/page_action.html"
},
"permissions": [
"tabs",
"*://*.google.com/"
],
"content_scripts": [
{
"matches": [
"https://*/*",
"http://*/*"
],
"run_at": "document_start",
"js": [
"src/inject/inject.js"
]
}
]
}