views:

78

answers:

3

I am trying to build some sort of logger functionality in JS. Is there any API for getting its own filename?

+1  A: 

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.

hsz
A: 

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() { ... }
dereli
+1  A: 

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.

pawel
The first approach seeemed very good, but it's not working.
dereli