How to get the absolute path of the current javascript file name

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.


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>

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

Tags:

Javascript