tags:

views:

61

answers:

4

Lets say I have a page with this code on it on www.foo.com:

<script src="http://www.bar.com/script.js" />

Can I write code from within script.js that can check that it was served from bar.com? Obviously document.location.href would give me foo.com.

Thanks!

+2  A: 
var scripts = document.getElementsByTagName("script");

give you a collection of all the scripts in the page After this you can read their src property to find your target (I hope you know how the script is called)

for (var i=0, limit=scripts.lenght; i< limit; i++) {
    if (scripts[i].src.substr(<calculate your offset>) == scriptName) {
       // Have you found your script, extract your data
    }
}
Eineki
That won't tell if script.js is being __served__ from www.bar.com, just that the src was that. It doesn't account for redirects.
Eli Grey
Let's say it is a good starting point, though. You can dig further with a xhttprequest if you need to investigate redirection too.
Eineki
I think this is probably the best answer, given I know the scriptname. Seems like the bit I was really hoping for isn't available client-side, but this is a good workaround.
tlianza
+1  A: 

The only way to find out the location of a non-worker script is the non-standard error.fileName, which is only supported by Firefox and Opera:

var loc = (new Error).fileName;

If the script is a worker thread (which of course it isn't), then you could just use the location object.

Eli Grey
+1  A: 

If it's really important, you could work around it by defining a string containing the script URL in front of each script tag:

<script type="text/javascript">SCRIPT_URL = "http://www.bar.com/script.js"&lt;/script&gt;
<script src="http://www.bar.com/script.js" />

Inside the script file you can then access the URL

alert("my URL is "+SCRIPT_URL);

Not too elegant but should work.

You could also, if you have a server-side language like PHP and don't mind sending JS files through the interpreter (Big performance caveat!), do something like this within the JS file:

<script type="text/javascript">var my_url = "<? echo $_SERVER["REQUEST_URI"]; ?>"</script>

but that should really, really be the last resort.

Pekka
A: 

You can wrap your script in a condition, kind of like an adult diaper, if you insist.

if(top.location.host==='www.bar.com'){
//the whole script goes here
}

else alert('Nyah Nyah Nyah!')
kennebec
I want the script to load, no matter where it's being hosted (it's going to be DNS CNAME'd from a bunch of hosts) I just need to track where it's being served from so it can create URLs to resources on it's own domain.
tlianza