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

4
  • 1
    Duplicate of: stackoverflow.com/questions/710957/… Commented Jun 22, 2010 at 23:06
  • 2
    Also see stackoverflow.com/questions/3019112/… Commented Jun 22, 2010 at 23:30
  • Does the JS know its own file name? Commented Jun 23, 2010 at 0:46
  • Indeed, it's addressed similarly in other places. And the answers are similar to below, which are good ideas. Thanks! Commented Jun 23, 2010 at 4:44

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

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
Without jquery document.querySelector('script[src$="serveAd.js"]).src
@gman good response but there's a typo. Should be document.querySelector('script[src$="serveAd.js"]').src with the closing single quote
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.)
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);

2 Comments

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).
This will fail if the script is loaded async (which is becoming more popular).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.