开发者

Can I get the location of where a JavaScript library is loaded from, from within the script?

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

<script src="http://www.bar.com/script.js" /&g开发者_如何学编程t;

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!


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
    }
}


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜