How to get result of console.trace() as string in javascript with chrome or firefox?

I’m not sure about firefox, but in v8/chrome you can use a method on the Error constructor called captureStackTrace. (More info here)

So a hacky way to get it would be:

var getStackTrace = function() {
  var obj = {};
  Error.captureStackTrace(obj, getStackTrace);
  return obj.stack;
};

console.log(getStackTrace());

Normally, getStackTrace would be on the stack when it’s captured. The second argument there excludes getStackTrace from being included in the stack trace.

Leave a Comment