Tuesday, 4 January 2022

Intercept XHR and change request headers and url before send in JavaScript

I want to intercept all XHR requests being sent, and change their URL and headers before the request gets sent.
Found this similar question but there are no answers there.

I tried hooking XMLHttpRequest.prototype.open, But it only gives me access to the response:

(function () {
    var origOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function () {
        console.log(arguments); // prints method ("GET"), URL
        console.log(this); // prints response, responseText, responseURL, status, statusText, and onXXX handlers
        origOpen.apply(this, arguments);
    };
})();

Also tried hooking XMLHttpRequest.prototype.setRequestHeader, but it only gives me access to each header value being set, one by one, and I can't associate it to the URL of the request:

(function () {
    var origSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
    XMLHttpRequest.prototype.setRequestHeader = function (header, value) {
        console.log("header", header);
        console.log("value", value);
        origSetRequestHeader.apply(this, arguments);
    };
})();

I managed to hook XMLHttpRequest.prototype.send to set a custom header, but since I want to change an existing header key, it appends my new value instead of replacing the existing one. Other people encountered the same problem: 1, 2:

(function () {
    var origSend = XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.send = function () {
        arguments[1] = myNewUrl; // arguments[1] holds the URL
        this.setRequestHeader('existingHeaderKey', newHeaderValue)
        origSend.apply(this, arguments);
    };
})();

How can I accomplish this?



from Intercept XHR and change request headers and url before send in JavaScript

No comments:

Post a Comment