JavaScript - 如何获取调用脚本的URL? [英] JavaScript - How do I get the URL of script being called?
问题描述
我在文件 http://site1.com/index.html
中包含myscript.js,如下所示:
I include myscript.js in the file http://site1.com/index.html
like this:
<script src=http://site2.com/myscript.js></script>
在myscript.js中,我希望能够访问URL http://site2.com/myscript.js 。我想要这样的东西:
Inside "myscript.js", I want to get access to the URL "http://site2.com/myscript.js". I'd like to have something like this:
function getScriptURL() {
// something here
return s
}
alert(getScriptURL());
哪会警告 http://site2.com/myscript.js 如果从上面提到的index.html调用。
Which would alert "http://site2.com/myscript.js" if called from the index.html mentioned above.
推荐答案
来自 http://feather.elektrum.org/book/src.html :
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
变量 myScript
现在有脚本dom元件。您可以使用 myScript.src
获取src网址。
The variable myScript
now has the script dom element. You can get the src url by using myScript.src
.
请注意,这需要作为初步评估脚本。如果您不想污染Javascript命名空间,您可以执行以下操作:
Note that this needs to execute as part of the initial evaluation of the script. If you want to not pollute the Javascript namespace you can do something like:
var getScriptURL = (function() {
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
return function() { return myScript.src; };
})();
这篇关于JavaScript - 如何获取调用脚本的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!