tags:

views:

94

answers:

4

If I have a site, example.com, and a page on that site references a Javascript at subdomain.example.com/serveAd.js -- is there a way from within serveAd.js to know its own URL, or the domain from which it was downloaded?

(The JS can certainly know all about the page that called it. I want to know if the JS knows about its own origin.)

+2  A: 

You can read it from the script tag that includes it (Read the DOM).
But in what situation do you get a script you don't know from where it is?!

Itay Moav
Well, it's a script that queries back to its origin server via ajax (which is necessary due to browser security restrictions).It's for a family of sites running on a single instance, but under a number of different domains. If the script knows the domain from which it's served, it can know the correct ajax URL.
Matt Sherman
A: 
document.domain

and

window.location.hostname

should work

kgb
i didn't read the question well enough... i don't think js files are differentiated during runtime, so there is only page info
kgb
In that case you should simply delete your answer.
Marcel Korpel
+3  A: 

I'm pretty sure, as the script is parsed that the last <script> node available in the DOM will be the one being parsed.

Try this in an external JS to see:

var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length - 1];
alert(lastScript.src);
gnarf
+1  A: 

If you were using jquery, you could get the full url with this kind of thing:

var fullJsUrl= $('script[src$=serveAd.js]').attr('src');

If not using jquery, it may take more work, but you get the idea ;)

amir75
This is a nice way to do it.
Matt Sherman