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

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

提交回复
热议问题