1

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!

1

4 Answers 4

3
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
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
Let's say it is a good starting point, though. You can dig further with a xhttprequest if you need to investigate redirection too.
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.
1

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.

Comments

1

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"</script>
<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.

Comments

0

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!')

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.