How to get the file-path of the currently executing javascript code

后端 未结 10 880
南笙
南笙 2020-11-29 19:18

I\'m trying to do something like a C #include \"filename.c\", or PHP include(dirname(__FILE__).\"filename.php\") but in javascript. I know I can do

10条回答
  •  余生分开走
    2020-11-29 19:26

    I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.

    // Get script file location
    // doesn't work for older browsers
    
    var getScriptLocation = function() {
        var fileName    = "fileName";
        var stack       = "stack";
        var stackTrace  = "stacktrace";
        var loc     = null;
    
        var matcher = function(stack, matchedLoc) { return loc = matchedLoc; };
    
        try { 
    
            // Invalid code
            0();
    
        }  catch (ex) {
    
            if(fileName in ex) { // Firefox
                loc = ex[fileName];
            } else if(stackTrace in ex) { // Opera
                ex[stackTrace].replace(/called from line \d+, column \d+ in (.*):/gm, matcher);
            } else if(stack in ex) { // WebKit, Blink and IE10
                ex[stack].replace(/at.*?\(?(\S+):\d+:\d+\)?$/g, matcher);
            }
    
            return loc;
        }
    
    };
    

    You can see it here.

提交回复
热议问题