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

后端 未结 10 869
南笙
南笙 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:31

    Refining upon the answers found here:

    little trick

    getCurrentScript and getCurrentScriptPath

    I came up with the following:

    //Thanks to https://stackoverflow.com/a/27369985/5175935
    var getCurrentScript = function () {
    
        if ( document.currentScript && ( document.currentScript.src !== '' ) )
            return document.currentScript.src;
        var scripts = document.getElementsByTagName( 'script' ),
            str = scripts[scripts.length - 1].src;
        if ( str !== '' )
            return src;
        //Thanks to https://stackoverflow.com/a/42594856/5175935
        return new Error().stack.match(/(https?:[^:]*)/)[0];
    
    };
    
    //Thanks to https://stackoverflow.com/a/27369985/5175935
    var getCurrentScriptPath = function () {
        var script = getCurrentScript(),
            path = script.substring( 0, script.lastIndexOf( '/' ) );
        return path;
    };
    

提交回复
热议问题