Tutorial :Get request url from xhr object



Question:

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.


Solution:1

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.


Solution:2

If you are using jQuery, you can make use of the "beforeSend" function in the AJAX request to modify the jqXHR object. I.e.,

$.ajax({  ...  url: "http://some/url",  beforeSend: function(jqxhr, settings) { jqxhr.requestURL = "http://some/url"; },  ...  });  

The jqXHR object passed to the various callbacks will then have that variable, jqXHR.requestURL, which you can access.


Solution:3

With the following hack no wrapper is required:

var xhrProto = XMLHttpRequest.prototype,      origOpen = xhrProto.open;    xhrProto.open = function (method, url) {      this._url = url;      return origOpen.apply(this, arguments);  };  

Usage:

var r = new XMLHttpRequest();  r.open('GET', '...', true);  alert(r._url); // opens an alert dialog with '...'  


Solution:4

According to https://developer.mozilla.org/en/XmlHttpRequest, you can indeed get channel if you have elevated privileges; however, channel is non-standard (might not work in other browsers), and indeed the W3C specs at http://www.w3.org/TR/XMLHttpRequest/ do not mention channel nor any other way to "extract the request URL". I suspect, therefore, that there is no way to do so reasonably across browsers.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »