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

js_ picture js_ · Jul 16, 2011 · Viewed 62.1k times · Source

console.trace() outputs its result on console.
I want to get the results as string and save them to a file.

I don't define names for functions and I also can not get their names with callee.caller.name.

Answer

chjj picture chjj · Jul 16, 2011

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.