0

Assuming http://example.com/js/script.js fires an AJAX request against some relative URL, how do I get the absolute URL that ended up being requested?

For example, if I request image.png from http://example.com/js/script.js I'd expect to get back http://example.com/js/image.png. If, however, I requested /image.png from the same URL I'd expect to get back http://example.com/image.png.

This question is tricky for two reasons:

  1. I don't believe it's possible to get a script's URL from inside it. UPDATE: I incorrectly assumed that AJAX requests are issued relative to the script location. It turns out that they are issued relative to location.href. This simplifies the situation.
  2. I don't believe that XMLHttpRequest exposes the request URL, not to mention its absolute form.

Any ideas?

Gili
  • 86,244
  • 97
  • 390
  • 689

1 Answers1

1

I don't believe it's possible to get a script's URL from inside it.

For that, simply use location.href

A quick hack to get absolute url from a relative one could be :

function getAbsoluteURL(relative) {
    var a = document.createElement('a');
    a.href = relative;
    return a.href;
}

According to this question it could not work on Ie6 , but does it really matter ?

Community
  • 1
  • 1
grunk
  • 14,718
  • 15
  • 67
  • 108