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.


Error.stack is what you need. It works in Chrome and Firefox. For example

try { var a = {}; a.debug(); } catch(ex) {console.log(ex.stack)}

will give in Chrome:

TypeError: Object #<Object> has no method 'debug'
    at eval at <anonymous> (unknown source)
    at eval (native)
    at Object._evaluateOn (unknown source)
    at Object._evaluateAndWrap (unknown source)
    at Object.evaluate (unknown source)

and in Firefox:

@http://www.google.com.ua/:87 _firebugInjectedEvaluate("with(_FirebugCommandLine){try { var a = {}; a.debug() } catch(ex) {console.log(ex.stack)}\n};")
@http://www.google.com.ua/:87 _firebugEvalEvent([object Event])
@http://www.google.com.ua/:67

This will give a stack trace (as array of strings) for modern Chrome, Firefox, Opera and IE10+

function getStackTrace () {

  var stack;

  try {
    throw new Error('');
  }
  catch (error) {
    stack = error.stack || '';
  }

  stack = stack.split('\n').map(function (line) { return line.trim(); });
  return stack.splice(stack[0] == 'Error' ? 2 : 1);
}

Usage:

console.log(getStackTrace().join('\n'));

It excludes from the stack its own call as well as title "Error" that is used by Chrome and Firefox (but not IE).

It shouldn't crash on older browsers but just return empty array. If you need more universal solution look at stacktrace.js. Its list of supported browsers is really impressive but to my mind it is very big for that small task it is intended for: 37Kb of minified text including all dependencies.