如何获取当前javascript文件名的绝对路径

43

我有一个名为main.js的JavaScript文件。

main.js中,我想获取当前文件的绝对路径,类似于:

http://server/app/main.js

http://server/app/script/main.js

如何快速获取文件的绝对路径?


这个类似的问题有更准确和完整的答案 https://dev59.com/2nRC5IYBdhLWcg3wG9Xp - Yves M.
8个回答

45

您可以在以下链接中查看脚本集合:

var scripts = document.getElementsByTagName("script");

对于返回的scripts数组中的每个元素,您都可以访问其src属性。

当前执行的包含文件始终是scripts数组中的最后一个。因此,您可以在scripts[scripts.length-1]处访问它。

当然,这仅适用于初始代码运行时,并且不会在加载初始脚本之后调用的函数内有用。因此,如果您需要稍后可用的值,则需要将其保存到变量中。


如果我们已经包含了多个文件,它还能正常工作吗?那么每个JS文件如何显示自己的src路径呢? - xxbinxx
值得注意的是,您可能希望使用其他方式从“scripts”数组中获取所需的脚本。我使用这种方法,但有报告称,在Firefox(呕......)中,每隔一段时间就会加载另一个脚本,而此时我的逻辑会抓取该元素数组。明智的做法是获取最后3个或更多并循环遍历它们,找到您要查找的文件名。 - Collin Klopfenstein

25

获取JavaScript文件的当前路径名

将此代码放置在您的Apache目录下的/tmp文件夹中,并将其命名为test.html。 访问以下URL:

localhost/grader/test.html?blah=2#foobar

Javascript:

<html>
<script>
  alert(location.pathname);  // /tmp/test.html
  alert(location.hostname);  // localhost
  alert(location.search);    // ?blah=2
  alert(document.URL);       // http://localhost/tmp/test.html?blah=2#foobar
  alert(location.href);      // http://localhost/tmp/test.html?blah=2#foobar
  alert(location.protocol);  // http:
  alert(location.host);      // localhost
  alert(location.origin);    // http://localhost
  alert(location.hash);      // #foobar
</script>                            
</html>

有关位置属性的更多信息: http://www.w3schools.com/jsref/obj_location.asp

或者如果您有jQuery:


<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script>
  $(location).attr('href');      // http://localhost/tmp/test.html?blah=2#foobar
  $(location).attr('pathname');  // /tmp/test.html
</script>
</html>

2

这样做是可以的。但它需要你已经知道脚本文件的文件名。但在大多数情况下,你应该是已经知道了文件名的。

function absFileLoc(filename) {
  var scriptElements = document.getElementsByTagName('script');
  for (var i = 0; i < scriptElements.length; i++) {
    var source = scriptElements[i].src;
    if (source.indexOf(filename) > -1) {
      var location = source.substring(0, source.indexOf(filename)) + filename;
      return location;
    }
  }
  return false;
}

这里是函数以及一个获取CSS文件绝对位置的函数。https://gist.github.com/jamrizzi/44bac4240057b4a89a2d918d05680e3d - Clay Risser

2

现代方式

获取绝对路径的最快方法是使用document.currentScript

const url = document.currentScript.src;

此外,您可以使用URL来读取url的组件。 :)
const url = new URL('http://www.example.com/cats');
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"

所有现代浏览器都应该支持这些方法。


1

0

非常简单

将此代码放入您想要获取路径的*.js文件中:

let scripts = document.getElementsByTagName('script')
let lastScript = scripts[scripts.length -1]
console.log('lastScript', lastScript.src)

0

我知道这是一个较旧的问题,但仍然很实际,因为IE仍未提供脚本src。

对我来说最好的方法是给脚本标签一个唯一的id:

    <script id="kuvaScript" src="jscripts/kuva/kuva.min.js"></script>

在脚本中我使用:

    var thisScript = $("#kuvaScript").attr("src");
    var thisPath = thisScript.split('/').slice(0, -1).join('/')+'/'; 

它将保持src格式不变(相对或完整),并已在IE和Chrome中进行了测试。

希望它能为您节省大量时间。


-2

如果你想获取当前文件名或目录,可以尝试这个方法

location.href.split('/')[ location.href.split('/').length - 1 ];


location.href获取的是当前网页的URL,而不是当前正在执行的JavaScript文件。 - CpnCrunch
我们首先获取URL,然后将其拆分以获取所需部分。 location.href.split('/')[0];//获取第一部分 location.href.split('/')[location.href.split('/').length-1];//获取文件名 - Amr
不,那是不正确的。你获取的是页面的URL,而不是当前的JavaScript文件。如果你把这段JavaScript代码放到一个名为www.abc.com/file.js的文件中,并将其包含在www.def.com/page.html中,location.href将返回www.def.com/page.html。问题是要求如何获取JavaScript文件的名称,即www.abc.com/file.js。 - CpnCrunch
你在控制台窗口试过我的代码了吗?对我来说它运行得很好! - Amr
是的,我尝试过了,它给出的是 .html 而不是 .js 的位置。你自己试试就知道了! - CpnCrunch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接