Get request url from xhr object

Viewed 48384

Is there any way to extract the request url from an xhr object? I can see the url in firebug via the channel property but you cant query this using javascript.

6 Answers

I hope I'm understanding your problem correctly.

It should be fairly simple to wrap your XHR objects with your own object to allow for this kind of functionality.

Below is an overly simplified example:

// Assumption: GetXHR() returns a new XHR object, cross browser.

function HTTPGet(url, onStartCb, onCompleteCb)
{
  var xhr = GetXHR();
  // Construct your own xhr object that contains the url and the xhr object itself.
  var myXhr = { xhr: xhr, url: url };

  xhr.onreadystatechange = function()
  {
     if (xhr.readyState == 4 && xhr.status == 200)
     {
        onCompleteCb(myXhr);
     }
  };

  xhr.open("GET", url);
  onStartCb(myXhr);
  xhr.send(null);
}

I haven't tested this extensively, but it should work and with some modifications (error handling, passing parameters, etc) you should probably be able to turn this example into a fully functional solution.

I also needed this because I was executing a for loop where I did URL requests.

Since usually you have the URL request before you call the open method on the XMLHttpRequest object, you can assign a random property on the xml object (in my case, the property url):

var xml = new XMLHttpRequest();
xml.onreadystatechange = function() {
    if ( xml.readyState == 4) {
        console.log(xml.url); // equal to originalUrl
    }
};
xml.open("GET", originalUrl, true);
xml.url = originalUrl;
xml.send();
Related