How might I get the script filename from within that script?
Asked Answered
G

13

63

I'm pretty sure the answer is no, but thought I'd ask anyway.

If my site references a scripted named "whatever.js", is it possible to get "whatever.js" from within that script? Like:

var scriptName = ???

if (typeof jQuery !== "function") {
    throw new Error(
        "jQuery's script needs to be loaded before " + 
        scriptName + ". Check the <script> tag order.");
}

Probably more trouble than it's worth for dependency checking, but what the hell.

Grommet answered 2/4, 2009 at 18:16 Comment(7)
Since you are going to be typing that line into the file somewhere, couldn't you just type in the name of the file you're adding it to?Cristycriswell
Yeah, that works, unless the filename is changed. I'm probably just being too pedantic.Grommet
Heh, if someone wants to submit "fuss less" and that gets a couple upvotes, I'd accept that as the answer. :DGrommet
Specifying 'var scriptName = ...' inside each script probably isn't the greatest idea. The way you are declaring it, scriptName is a global variable. It would work better if you used closures. jibbering.com/faq/faq%5Fnotes/closures.htmlCleanser
The other advantage to this is if you want to get the full URL-path to the running script. Not all .js files are served from the same domain as the html pages that use them.Coagulase
See also Get script path and What is my script src URL?Brothel
I'd love to see something that works with PhantomJSCongius
S
40
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
var scriptName = lastScript.src;
alert("loading: " + scriptName);

Tested in: FF 3.0.8, Chrome 1.0.154.53, IE6


See also: How may I reference the script tag that loaded the currently-executing script?

Sig answered 2/4, 2009 at 18:25 Comment(4)
Edge case: If the current script was added to <head> after <body> is loaded and there are any scripts in <body> this will return the last script in the <body>, not the currently running script that's in <head>.Cradle
I have come across a case where this algorithm doesn't work reliably. Other script tags that are set to async can run between your script being requested and run. These scripts can add other scripts to the DOM which appear after yours. When your script run the last script on the page is no longer yours and the wrong src is returned.Carolanncarole
This answer is seriously out of date. Scripts can be deferred, async, modules, workers. This answer works in none of them.Splashdown
I feel like document.currentScript should be mentioned here, but like @Splashdown said this answer is out of date overall and the algorithm does not cover many edge cases.Foulard
T
27

I'm aware this is old but I have developed a better solution because all of the above didn't work for Async scripts. With some tweaking the following script can cover almost all use cases. Heres what worked for me:

function getScriptName() {
    var error = new Error()
      , source
      , lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/)
      , currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/);

    if((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] != "")
        return source[1];
    else if((source = currentStackFrameRegex.exec(error.stack.trim())))
        return source[1];
    else if(error.fileName != undefined)
        return error.fileName;
}

Not sure about support on Internet Explorer, but works fine in every other browser I tested on.

Tychonn answered 6/11, 2013 at 8:44 Comment(11)
Thanks! Exactly what I was looking for! Interesting that sometimes the same approach with error's stack appears in python or Java code.Canberra
Thanks! that's a great approach as it works also in Web Workers. However it fails after minification because the function is not called getScriptName anymore. The solution is to replace the currentStackFrameRegex expression with: new RegExp(arguments.callee.name + ' \(.+\\/(.*):\\d+:\\d+\)')Anjanette
Very nice solution, sadly it does not work on IE10- :(Curson
@PsychoWood I'll take a look and update the answer if I find a solution.Tychonn
I see that I get the second line for currentStackFrameRegex but for me source[1] is an empty string.Troytroyer
It would be better to detect document.currentScript before doing the workaround.Impala
@Anjanette arguments.callee.name won't work If the function is defined as a function expression. I think the catch-all solution would be replacing arguments.callee.name with scriptName where scriptName is var scriptName = arguments.callee.name || 'getScriptName';. Of course, minification would change the variable name if the function expression is assigned to a normal variable, so one would have to assign the function to an object key to make this work.Marjie
@Marjie Another simpler solution would be to disable minification of that symbol.Tychonn
Update: On current Firefox version the above code doesn't work for me. I added another regex which caught the new case: /.+@(.*?):\d+:\d+/ (tested on ff 57).Anjanette
This looks very fragile and can potentially introduce performance issues or catastrophic backtracking depending on how your code looks. I would avoid this at almost all costs, or at least careful consider the importance in contrast to the potential implications of this.Waksman
@MathiasLykkegaardLorenzen Things that can't be done out of the box, and are complex to achieve, usually are fairly fragile. That said, I've been using this snippet (or at least a variation of it) for the last 4 years on a number of sites and it is still working fine. YMMV.Tychonn
I
22

You can use...

var scripts = document.getElementsByTagName("script"),
  currentScriptUrl = (document.currentScript || scripts[scripts.length - 1]).src;

currentScript() is supported by all browsers except IE.

Make sure it's ran as the file is parsed and executed, not on DOM ready or window load.

If it's an empty string, your script block has no or an empty src attribute.

Impala answered 18/5, 2012 at 16:31 Comment(3)
Not directly related to answer, but the famous caniuse.com doesn't monitor document.currentScript yet. An issue has been opened however. To make this feature appear on caniuse.com, you can vote up: github.com/Fyrd/caniuse/issues/1099.Work
I like that this is useful even in async scripts, unlike some other answers. Unfortunately, if currentScript is called in an event handler or global function that itself is called from another file, it will return that other file.Dvandva
Further to the comment by @Stephan, there is now an entry for document.currentScript at caniuse.com.Homemaker
M
11

In Node.js:

var abc = __filename.split(__dirname+"/").pop();
Montagu answered 24/4, 2017 at 11:16 Comment(4)
I tried this but I got __filename is not defined... am I using it wrong?Zygosis
Apparently __filename and __dirname are node.js things, and only work in a node.js context.Montagu
@JoãoCiocca Adding to Alichino's comment the js client side cannot see the -server - filesystem whereas Node can. Thanks Alichino for thinking of the server side js.Fireboat
You should add that abc first creates an array with two elements and then throws away the first element.Fireboat
S
5

Shog9's suggestion more shorter:

alert("loading: " + document.scripts[document.scripts.length-1].src);
Sousa answered 8/9, 2013 at 22:39 Comment(0)
P
3

You can return a list of script elements in the page:

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

And then evaluate each one and retrieve its location:

var location;

for(var i=0; i<scripts.length;++i) {
   location = scripts[i].src;

   //Do stuff with the script location here
}
Peal answered 2/4, 2009 at 18:27 Comment(0)
T
3

As the "src" attribute holds the full path to the script file you can add a substring call to get the file name only.

var path = document.scripts[document.scripts.length-1].src;

var fileName = path.substring(path.lastIndexOf('/')+1);
Tighe answered 30/10, 2015 at 12:23 Comment(0)
R
1

I had issues with the above code while extracting the script name when the calling code is included inside a .html file. Hence I developed this solution:

var scripts = document.getElementsByTagName( "script" ) ;
var currentScriptUrl = ( document.currentScript || scripts[scripts.length - 1] ).src ;
var scriptName = currentScriptUrl.length > 0 ? currentScriptUrl : scripts[scripts.length-1].baseURI.split( "/" ).pop() ; 
Rendering answered 28/11, 2015 at 15:42 Comment(0)
R
1

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 variable will contain the full path of the JavaScript file, the filename can be parsed from that. Tested in IE11, but it should work elsewhere.

Randyranee answered 8/11, 2016 at 16:33 Comment(0)
T
1

If you did't want use jQuery:

function getCurrentFile() {
    var filename = document.location.href;
    var tail = (filename.indexOf(".", (filename.indexOf(".org") + 1)) == -1) ? filename.length : filename.lastIndexOf(".");
    return (filename.lastIndexOf("/") >= (filename.length - 1)) ? (filename.substring(filename.substring(0, filename.length - 2).lastIndexOf("/") + 1, filename.lastIndexOf("/"))).toLowerCase() : (filename.substring(filename.lastIndexOf("/") + 1, tail)).toLowerCase();
}
Tanguay answered 6/4, 2018 at 6:57 Comment(0)
H
0

What will happen if the jQuery script isn't there? Are you just going to output a message? I guess it is slightly better for debugging if something goes wrong, but it's not very helpful for users.

I'd say just design your pages such that this occurrence will not happen, and in the rare event it does, just let the script fail.

Huoh answered 3/4, 2009 at 10:38 Comment(1)
Yes, I throw new Error() with a "include the script dumbass!" message. My feeling is that it's just good practice. People tend to slack on things like this because it's a dynamic language. I'll sleep better this way though. The extra 100 bytes are worth it to me. :)Grommet
L
0

The only way that is waterproof:

var code = this.__proto__.constructor.toString();
$("script").each(function (index, element) {
    var src = $(element).attr("src");
    if (src !== undefined) {
        $.get(src, function (data) {
            if (data.trim() === code) {
                scriptdir = src.substring(0, src.lastIndexOf("/"));
            }
        });
    }
});

"var code" can also be the function name, but with the prototype constructor you don't have to modify anything. This code compares its own content against all present scripts. No hard coded filenames needed anymore. Korporal Nobbs was in the right direction, but not complete with the comparison.

Loyceloyd answered 22/12, 2020 at 16:3 Comment(0)
R
0

Using the javascript stack trace from Error object, you can extract the line 2 and do some substring and splits like below. The output will be the filename where the code is executed. This sample code assumes that you are executing on the same javascript. To determine the script that calls your script, you can try change the level to 2 like so. split('\n')[2]

let stack1 = new Error().stack.trim().split('\n')[1].trim()
console.log(stack1.substring(stack1.lastIndexOf('/')+1).split('?')[0])
Rizika answered 8/10, 2023 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.