43

I have a javascript file named main.js.

Inside main.js I want to get the absolute path of this current file, something like:

http://server/app/main.js

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

What is the fastest way to get the absolute path?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
hguser
  • 35,079
  • 54
  • 159
  • 293
  • This similar question has more accurate and complete answers https://stackoverflow.com/q/403967/1480391 – Yves M. Oct 15 '18 at 13:00

8 Answers8

45

You can investigate script collection at:

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

For each element in the returned scripts array you can access its src attribute.

The currently executing include file will always be the last one in the scripts array. So you can access it at scripts[scripts.length-1].

Of course this will only work at time of initial code run and would not be useful for example within a function that is called after initial script is loaded, so if you need the value available later, you would need to save it to a variable.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • Will it work if we have included multiple files... then how will each js file show it's own src path.. ?? – xxbinxx Sep 05 '14 at 07:26
  • Worth noting that you might want to use another means of getting the script you want out of the `scripts` array. I use this method, but am having reports that every so often in Firefox (blegh...) there's another script that's been loaded by the time my logic grabs that array of elements. The smart thing to do would be to grab like the last 3 or so and loop through them and find the one with the filename you're looking for. – Collin Klopfenstein Mar 30 '15 at 20:47
25

Get the current pathname of the javascript file

Put this in your apache directory underneath /tmp and call it test.html. Visit the 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>

More information on attributes of location: http://www.w3schools.com/jsref/obj_location.asp

Or if you have 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>
Matt Cromwell
  • 375
  • 2
  • 9
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
2

This will work. However, it requires that you already know what the filename of the script is. But in most situations you would know that.

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;
}
Clay Risser
  • 3,272
  • 1
  • 25
  • 28
  • Here is the function along with one that gets the absolute location of css files . https://gist.github.com/jamrizzi/44bac4240057b4a89a2d918d05680e3d – Clay Risser Jun 12 '16 at 20:44
2

Modern way

The fastest way to get the absolute path is to use document.currentScript

const url = document.currentScript.src;

Also to read components of a url you can use URL :)

const url = new URL('http://www.example.com/cats');
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"

All modern browsers should support these methods.

Igor Sukharev
  • 2,467
  • 24
  • 21
1
var path = document.location.pathname

will provide the current html page.

if you look for the current script, try the way mentioned in this site:

http://bencarpenter.co.uk/javascript-path-to-the-current-script

rhavin
  • 1,512
  • 1
  • 12
  • 33
0

I know this is an older question, but still actual because IE still not provides the script src.

The best form me was to give the script tag an unique id:

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

Inside the script i use:

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

It will keep the src format as it is (relative or complete) and was tested in IE and Chrome.

Hope it will save you a lot of time.

Henry
  • 1,242
  • 1
  • 12
  • 10
0

Very easy

Put this in the *.js file you want to get path:

let scripts = document.getElementsByTagName('script')
let lastScript = scripts[scripts.length -1]
console.log('lastScript', lastScript.src)
CommonSenseCode
  • 23,522
  • 33
  • 131
  • 186
-2

Try this if you want to get the current file name or directory

location.href.split('/')[ location.href.split('/').length - 1 ];
Amr
  • 574
  • 1
  • 11
  • 15
  • location.href gets the url of the current web page, not the currently executing javascript file. – CpnCrunch Sep 12 '17 at 18:21
  • we first get the url, than split it to get the desired part. location.href.split('/')[ 0 ]; //gets the first part location.href.split('/')[ location.href.split('/').length - 1 ]; //gets the file name – Amr Sep 14 '17 at 19:46
  • No, that's incorrect. You're getting the url of the page, not the current javascript file. If you put that javascript code into a file www.abc.com/file.js which is included in www.def.com/page.html, location.href will return www.def.com/page.html. The question is asking how to get the name of the javascript file, i.e. www.abc.com/file.js. – CpnCrunch Sep 15 '17 at 20:07
  • Did you tried my code in the console window?? For me it worked fine! – Amr Sep 19 '17 at 03:12
  • Yes, I tried, and it gives the .html rather than .js location. Try yourself and you'll see! – CpnCrunch Sep 19 '17 at 17:34