no-image

javascriptで現在実行中のファイル名及び行番号を取得する方法

qiitaにも書いたけど、こっちにも載せておく。

Object.defineProperty(window, '__STACK__', {
get: function(){
var orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack){ return stack; };
var err = new Error;
Error.captureStackTrace(err, arguments.callee);
var stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
}
});
Object.defineProperty(window, '__FILE__', {
get: function(){
let filename = __STACK__[1].getFileName().replace(location.origin, "").replace(window.location.search, "");
if(!filename) filename = "/";
return filename;
}
});
Object.defineProperty(window, '__LINE__', {
get: function(){
return __STACK__[1].getLineNumber();
}
});
Object.defineProperty(window, '__HERE__', {
get: function(){
let filename = __STACK__[1].getFileName().replace(location.origin, "").replace(window.location.search, "");
if(!filename) filename = "/";
return filename + ":" + __STACK__[1].getLineNumber();
}
});
console.log("__FILE__", __FILE__);
console.log("__LINE__", __LINE__);
console.log("__HERE__", __HERE__);