Alec Smart
Alec Smart

Reputation: 95890

Detect location of script not the page where it is called from

I am wondering if I can somehow find out the location of the script and not the page it is called from. e.g. if the page is http://xxx.yyy.com/a.htm, and I write location.href, I get that location instead of http://aaa.zzz.com/script.js where the script resides. Is it possible to get the location of the script?

Thank you for your time.

Upvotes: 2

Views: 282

Answers (3)

will
will

Reputation: 4063

I had to do this exact same thing just now and came up with a slightly different solution that's working well for me. Do you own the page that the script is being referenced in? If so, you can put an id on that script element. Then in your javascript file, you can get that element and parse it "src" attribute for the domain.

Upvotes: 1

Quentin
Quentin

Reputation: 943515

Short answer: No.

Long answer: You could loop over all the elements in the page, calculate an absolute URI for each, then make a JSON-P request to a server side script on a server you control that will download each script and compare it to a master copy — but that would break if the script was changed in any way. A more robost solution might be achievable with a smarter comparison algorithum, but you'll never get 100% reliability (since there might be two copies of the same script included which you wouldn't be able to distinguish).

Upvotes: 1

ajm
ajm

Reputation: 20105

You could always grab the script tag itself and parse out the src attribute.

var scripts = document.getElementsByTagName('script');
for(var i = 0; i < scripts.length; i++){
    alert(scripts[i].src); 
}

Upvotes: 0

Related Questions