21

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.)

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Matt Sherman
  • 8,298
  • 4
  • 37
  • 57

2 Answers2

15

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 ;)

laher
  • 8,860
  • 3
  • 29
  • 39
  • 3
    Not sure if this is due to the changes in jquery since this question, but now this only works for me with $('script[src$="serveAd.js"]').attr('src'); // quotes around the file name – atmd Jan 15 '15 at 08:31
  • 1
    Without jquery `document.querySelector('script[src$="serveAd.js"]).src` – gman Jan 30 '19 at 06:56
  • 1
    @gman good response but there's a typo. Should be `document.querySelector('script[src$="serveAd.js"]').src` with the closing single quote – giuliolunati Mar 24 '19 at 13:08
  • 1
    This will find the first script file which name ends with "serveAd.js". So this will fail if there is multiple scripts like that (such as a "dont-serveAd.js" before "serveAd.js"). It will also fail if the script has been renamed for some reason. (But this name was given in the question, so not a problem in this case.) – Peter Jan 30 '20 at 14:03
6

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
  • 105,192
  • 25
  • 127
  • 161
  • 5
    Not if the script file was loaded using createElement/appendChild, then it could be anywhere in the DOM (depending on where you appended it to). – bart Oct 05 '11 at 13:37
  • This will fail if the script is loaded async (which is becoming more popular). – Peter Jan 30 '20 at 14:04