11

I am trying to build some sort of logger functionality in javascript. Is there any API for a script to get its own filename?

3

7 Answers 7

19

This should work: (new Error).fileName

Or you can try this:

var filepath;
(function(){ 
    var scripts = document.getElementsByTagName('script'); 
    filepath = scripts[ scripts.length-1 ].src; 
}());

The second option gives you the path of your script file.

Sign up to request clarification or add additional context in comments.

6 Comments

The second approach will conflict with some services like Google Analytics, or New Relic, because they add a script at the end!
@sumid, could you explain?
@pawel the problem is in the position [scripts.length-1]. You assume that your script is the last in scripts. This is not true when there is some service which adds some scripting afterwards. Then you don't get src of your script but src of the added script which would be typically null.
I know for sure it's the last one at the moment of execution. Scripts are interpreted synchronously while the document is parsed, the (function(){}()) construct means it's executed immediately, and the script being executed at this very moment is the last one in the DOM, as nothing after it hasn't been parsed yet. However, and maybe I should edit my answer to reflect that, this won't work using deferred/asynchronously loaded <script> elements.
Ok, sorry, my mistake. Probably I had some problems with async. In the end I used the hard-coded way as stated in the response above.
|
9

If we can get the current script's tag, then we can read its src attribute. Excerpt from https://stackoverflow.com/a/22745553/4396817 below:

document.currentScript will return the element whose script is currently being processed.

<script>
  var me = document.currentScript;
</script>

Benefits

  • Simple and explicit. Reliable.
  • Don't need to modify the script tag
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Problems

  • Will not work in older browsers and IE.

...So from there, we can simply read the src attribute!

<script src="http://website.com/js/script.js">
  alert(document.currentScript.src);
</script>

// Alerts "http://website.com/js/script.js"

1 Comment

To the casual reader, help the feature reported here monitored on caniuse.com. Upvote here: github.com/Fyrd/caniuse/issues/1099.
6

I see two ways:

  • put into every JS file a variable var filename = 'script.js';
  • get the filename using <script> tag name

JS can not get filename like bash/perl/c scripts.

1 Comment

"put into every JS file a variable var filename = 'script.js';" But not at global scope, because the last-loaded one will win. So if you have a.js and b.js and load them both, and call a function in a, it will be tricked into thinking it's b.
0

Unfortunately this is not possible.

If you change your approach, getting function names may help you which is sometimes possible. Your best chance would be extracting function name from "arguments.callee". This only works if function is defined like

function FN() { ... }

And does not work when

var FN = function() { ... }

Comments

0

this is my modification that fixes a few possible issues, but adds a requirement.

It needs you to name the file in a certain way, so for example if you have a .js file, but you want to know which version is loaded (for example to tell a php server). so your js file would be "zoom_v34.js".

    var version;
    (function(){
        var scripts = document.getElementsByTagName('script');
        for (var i=0; i<scripts.length; i++) {
            var start = scripts[i].src.indexOf('zoom_');
            if (start != -1) { var end = scripts[i].src.indexOf('.',start); version = scripts[i].src.substr(start+6,end-start-6); break; }
        }
    }());
    post='login{JS:'+version+'}';

2 Comments

This probably isn't the best solution, especially since there appears to be a better one already
it's not the best solution. it is good when you add the script in different ways, doesn't assume it's the last script, works more reliably with complicated fringe cases, as it enumerates the whole array instead of assuming it's the last.
0

You can try putting this at the top of your JavaScript file:

window.myJSFilename = "";
window.onerror = function(message, url, line) {
    if (window.myJSFilename != "") return;
    window.myJSFilename =  url;
}
throw 1;

Make sure you have only functions below this. The myJSFilename global variable will contain the full path of the JavaScript file, and the filename can be parsed from that. Tested in IE11, but it should work elsewhere.

Comments

0

This works for me.

document.currentScript.src

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.