How to get JavaScript caller function line number? How to get JavaScript caller source URL?
This works for me in chrome/QtWebView
function getErrorObject(){
try { throw Error('') } catch(err) { return err; }
}
var err = getErrorObject();
var caller_line = err.stack.split("\n")[4];
var index = caller_line.indexOf("at ");
var clean = caller_line.slice(index+2, caller_line.length);
kangax's solution introduces unnecessary try..catch scope. If you need to access the line number of something in JavaScript (as long as you are using Firefox or Opera), just access (new Error).lineNumber
.
I was surprised that most of these answers assumed that you wanted to handle an error rather than just output helpful debug traces for normal cases as well.
For example, I like using a console.log
wrapper like this:
consoleLog = function(msg) {//See https://stackoverflow.com/a/27074218/470749
var e = new Error();
if (!e.stack)
try {
// IE requires the Error to actually be thrown or else the
// Error's 'stack' property is undefined.
throw e;
} catch (e) {
if (!e.stack) {
//return 0; // IE < 10, likely
}
}
var stack = e.stack.toString().split(/\r\n|\n/);
if (msg === '') {
msg = '""';
}
console.log(msg, ' [' + stack[1] + ']');
}
This ends up printing an output such as the following to my console:
1462567104174 [getAllPosts@http://me.com/helper.js:362:9]
See https://stackoverflow.com/a/27074218/ and also A proper wrapper for console.log with correct line number?