Can javascript file get its own name?
Asked Answered
Z

7

10

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

Zipporah answered 8/12, 2009 at 9:55 Comment(3)
Is this what you're asking? https://mcmap.net/q/95184/-what-is-my-script-src-urlCankerworm
No I am just trying to have a logger where I can have timestamp, some string, line number, and the js file name etc. Let me try out the solutions given.Zipporah
Possible duplicate of How may I reference the script tag that loaded the currently-executing script?Provided
S
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.

Supinate answered 8/12, 2009 at 12:21 Comment(5)
The second approach will conflict with some services like Google Analytics, or New Relic, because they add a script at the end!Cardona
@sumid, could you explain?Supinate
@Supinate 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.Cardona
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.Supinate
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.Cardona
D
8

If we can get the current script's tag, then we can read its src attribute. Excerpt from https://mcmap.net/q/68003/-how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script 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"
Doorn answered 27/9, 2015 at 6:41 Comment(1)
To the casual reader, help the feature reported here monitored on caniuse.com. Upvote here: github.com/Fyrd/caniuse/issues/1099.Provided
C
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.

Carnay answered 8/12, 2009 at 10:2 Comment(1)
"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.Gharry
S
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() { ... }
Senskell answered 8/12, 2009 at 10:14 Comment(0)
C
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+'}';
Catchy answered 27/9, 2015 at 6:10 Comment(2)
This probably isn't the best solution, especially since there appears to be a better one alreadyLomeli
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.Catchy
R
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.

Rig answered 8/11, 2016 at 16:25 Comment(0)
H
0

This works for me.

document.currentScript.src
Hulton answered 20/3 at 8:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.