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

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

    Within the script:

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

    This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:

    (function() { ... })();
    
    0 讨论(0)
  • 2020-11-29 19:23

    I just made this little trick :

    window.getRunningScript = () => {
        return () => {      
            return new Error().stack.match(/([^ \n])*([a-z]*:\/\/\/?)*?[a-z0-9\/\\]*\.js/ig)[0]
        }
    }
    
    console.log('%c Currently running script:', 'color: blue', getRunningScript()())
    

    Works on: Chrome, Firefox, Edge, Opera

    Enjoy !

    0 讨论(0)
  • 2020-11-29 19:24

    All browsers except Internet Explorer (any version) have document.currentScript, which always works always (no matter how the file was included (async, bookmarklet etc)).

    If you want to know the full URL of the JS file you're in right now:

    var script = document.currentScript;
    var fullUrl = script.src;
    

    Tadaa.

    0 讨论(0)
  • 2020-11-29 19:25

    The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target <script> tags with a [src] attribute.

    /**
     * Current Script Path
     *
     * Get the dir path to the currently executing script file
     * which is always the last one in the scripts array with
     * an [src] attr
     */
    var currentScriptPath = function () {
    
        var scripts = document.querySelectorAll( 'script[src]' );
        var currentScript = scripts[ scripts.length - 1 ].src;
        var currentScriptChunks = currentScript.split( '/' );
        var currentScriptFile = currentScriptChunks[ currentScriptChunks.length - 1 ];
    
        return currentScript.replace( currentScriptFile, '' );
    }
    

    This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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;
    };
    
    0 讨论(0)
提交回复
热议问题