Search code examples
javascriptxmlhttprequest

Obtain the method and url from an XHR


Basically what the title says, I want to get the URL and HTTP Verb from a xhr. Is this possible?


Solution

  • Not natively, I'm afraid. In prototypable implementations you could write your own prototype:

    XMLHttpRequest.prototype.__oldOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.verb = "";
    XMLHttpRequest.prototype.url  = "";
    XMLHttpRequest.prototype.open = function (verb, url, async)
    {
        this.verb = verb;
        this.url  = url;
        this.__oldOpen.call(this, verb, url, async); 
    }
    

    Don't expect it to work in IE7 and older though.


    I suppose you could do it by completely recreating the XMLHttpRequest object, but it would take a lot of work to get it right:

    var oldXHR = XMLHttpRequest;
    function XMLHttpRequest()
    {
        var realXHR = new oldXHR();
        this.onreadystatechange = function () {}
        this.open = function (verb, url, async)
        {
            this.verb = verb;
            this.url  = url;
            realXHR.open(verb, url, async);
        {
        this.send = function () { realXHR.send(); }
    
        // all other properties and methods... 
    }
    

    Of course, you have to go to the effort of correctly binding onreadystatechange and setting the status, etc.