Search code examples
javascriptxmlhttprequest

Get URL inside function that decorate method onreadystatechange of XMLHttpRequest


I need to add a special header to all requests sent using XMLHttpRequest in my project. I achieved this by decorating onreadystatechange the method of XMLHttpRequest:

XMLHttpRequest = new Proxy(XMLHttpRequest, {
    construct: function (target, args) {
        const xhr = new target(...args);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 1) {
                xhr.setRequestHeader('header name', 'header value');
            }
        };
        return xhr;
    },
});

But it turned out that I don't need to do this for all urls. I need to determine if the url meets some requirements. And if yes, then add a header to the request, otherwise do not change the request. If there is a way to get the url to which the request is being made while inside the function that overrides the method onreadystatechange (see the code above)


Solution

  • You can override XMLHttpRequest.prototype.send method and save the url along with the XMLHttpRequest instance when it's invoked. The send method seems to be the only way to provide url to an XHR instance.

    __originMethod = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (method, url, ...args) {
      this.__url = url; //save the url into the instance
      __originMethod.call(this, method, url, ...args);
    }
    

    Then you can access __url property on xhr instance.