Can the code in the Javascript file know its own domain / url

If I have a site, example.com and a page on this site, a Javascript link to subdomain.example.com/serveAd.js - is there a way from inside serveAd.js to find out your own URL or domain from which it was downloaded ?

(JS, of course, can know everything about the page that called it. I want to know if JS knows about its origin.)

+16
javascript
Jun 22 '10 at 22:33
source share
2 answers

If you use jquery, you can get the full url with things like this:

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

If you don't use jquery, it might take more work, but you get the idea;)

+11
Jun 22 2018-10-22T00:
source share

I am sure that when the script is parsed, the last <script> node available in the DOM will be processed.

Try this in external JS to see:

 var scripts = document.getElementsByTagName('script'); var lastScript = scripts[scripts.length - 1]; alert(lastScript.src); 
+4
Jun 22 '10 at 22:40
source share



All Articles