JavaScript - 如何获取被调用脚本的 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2976651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - How do I get the URL of script being called?
提问by MikeC8
I include myscript.js in the file http://site1.com/index.htmllike this:
我将 myscript.js 包含在文件中,http://site1.com/index.html如下所示:
<script src=http://site2.com/myscript.js></script>
Inside "myscript.js", I want to get access to the URL "http://site2.com/myscript.js". I'd like to have something like this:
在“myscript.js”中,我想访问 URL“ http://site2.com/myscript.js”。我想要这样的东西:
function getScriptURL() {
// something here
return s
}
alert(getScriptURL());
Which would alert "http://site2.com/myscript.js" if called from the index.html mentioned above.
如果从上面提到的 index.html 调用,它会提醒“ http://site2.com/myscript.js”。
采纳答案by lambacck
From http://feather.elektrum.org/book/src.html:
来自http://feather.elektrum.org/book/src.html:
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
The variable myScriptnow has the script dom element. You can get the src url by using myScript.src.
该变量myScript现在具有脚本 dom 元素。您可以使用myScript.src.
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:
请注意,这需要作为脚本初始评估的一部分来执行。如果您不想污染 Javascript 命名空间,您可以执行以下操作:
var getScriptURL = (function() {
var scripts = document.getElementsByTagName('script');
var index = scripts.length - 1;
var myScript = scripts[index];
return function() { return myScript.src; };
})();
回答by tsds
You can add id attribute to your script tag (even if it is inside a head tag):
您可以将 id 属性添加到您的脚本标签(即使它在 head 标签内):
<script id="myscripttag" src="http://site2.com/myscript.js"></script>
and then access to its src as follows:
然后按如下方式访问其 src:
document.getElementById("myscripttag").src
of course id value should be the same for every document that includes your script, but I don't think it is a big inconvenience for you.
当然,包含您的脚本的每个文档的 id 值都应该相同,但我认为这不会给您带来很大的不便。
回答by dave1010
Everything except IE supports
除了 IE 支持的所有东西
document.currentScript
回答by QueueHammer
I wrote a class to find get the path of scripts that works with delayed loading and async script tags.
我编写了一个类来查找使用延迟加载和异步脚本标签的脚本的路径。
I had some template files that were relative to my scripts so instead of hard coding them I made created the class to do create the paths automatically. The full source is here on github.
我有一些与我的脚本相关的模板文件,因此我没有对它们进行硬编码,而是创建了类来自动创建路径。完整的源代码在 github 上。
A while ago I had use arguments.callee to try and do something similar but I recently read on the MDN that it is not allowed in strict mode.
不久前我曾使用 arguments.callee 尝试做一些类似的事情,但我最近在 MDN 上读到它在严格模式下是不允许的。
function ScriptPath() {
var scriptPath = '';
try {
//Throw an error to generate a stack trace
throw new Error();
}
catch(e) {
//Split the stack trace into each line
var stackLines = e.stack.split('\n');
var callerIndex = 0;
//Now walk though each line until we find a path reference
for(var i in stackLines){
if(!stackLines[i].match(/http[s]?:\/\//)) continue;
//We skipped all the lines with out an http so we now have a script reference
//This one is the class constructor, the next is the getScriptPath() call
//The one after that is the user code requesting the path info (so offset by 2)
callerIndex = Number(i) + 2;
break;
}
//Now parse the string for each section we want to return
pathParts = stackLines[callerIndex].match(/((http[s]?:\/\/.+\/)([^\/]+\.js)):/);
}
this.fullPath = function() {
return pathParts[1];
};
this.path = function() {
return pathParts[2];
};
this.file = function() {
return pathParts[3];
};
this.fileNoExt = function() {
var parts = this.file().split('.');
parts.length = parts.length != 1 ? parts.length - 1 : 1;
return parts.join('.');
};
}
回答by Mr. Pumpkin
if you have a chance to use jQuery, the code would look like this:
如果您有机会使用 jQuery,代码将如下所示:
$('script[src$="/myscript.js"]').attr('src');
回答by pery mimon
Simple and straightforward solution that work very well :
简单而直接的解决方案,效果很好:
If it not IE you can use document.currentScript
For IE you can do document.querySelector('script[src*="myscript.js"]')
so :
如果不是 IE 你可以使用document.currentScript
For IE 你可以这样document.querySelector('script[src*="myscript.js"]')
做:
function getScriptURL(){
var script = document.currentScript || document.querySelector('script[src*="myscript.js"]')
return script.src
}
回答by Varun Bhatia
Following code lets you find the script element with given name
以下代码可让您找到具有给定名称的脚本元素
var scripts = document.getElementsByTagName( 'script' );
var len = scripts.length
for(var i =0; i < len; i++) {
if(scripts[i].src.search("<your JS file name") > 0 && scripts[i].src.lastIndexOf("/") >= 0) {
absoluteAddr = scripts[i].src.substring(0, scripts[i].src.lastIndexOf("/") + 1);
break;
}
}
回答by Paul
Can't you use location.href or location.host and then append the script name?
您不能使用 location.href 或 location.host 然后附加脚本名称吗?

