I'm trying to create an http-interceptor that will allow to add header to requests sent from within third-party app. I'm monkey-patching XMLHttpRequest.send
const origSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
this.setRequestHeader("A-Header", "Value");
return origSend.apply(this, [].slice.call(arguments));
};
The problem is that I don't need that header in other requests, still I don't see how can I access request url (to check if request is made from third-party lib). How can I make this interceptor work only in case there's a substring in url?
If you also monkey-patch the .open() method, you can store the passed url in the instance and read it later:
const origOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function() {
this.url = arguments[1];
return origOpen.apply(this, [].slice.call(arguments));
};
const origSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
if (this.url) {
console.log("url found:", this.url);
this.setRequestHeader("A-Header", "Value");
}
// prevent error in snippet, uncomment next line
// return origSend.apply(this, [].slice.call(arguments));
};
const xhr = new XMLHttpRequest();
xhr.open("get", "https://stackoverflow.com");
xhr.send();