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

Viewed 72462

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.

7 Answers

you only need var stack = new Error().stack. this is simplified version of @sgouros answer.

function foo() {
  bar();
}
function bar() {
  baz();
}
function baz() {
  console.log(new Error().stack);
}

foo();

Probably will not work in every browser (works in Chrome).

I was trying to get Stack Trace as string variable in JavaScript on NodeJS and this tutorial helped me. This will work in your scenario as well except stack trace is printed via Error Object than console.trace().

Code to print stack trace:

function add(x, y) {
    console.log(new Error().stack);
    return x+y;
}
Related