Print current stack trace in JavaScript

The documentation says it could be done in the following way:

const targetObject = {};
Error.captureStackTrace(targetObject);
targetObject.stack;  // Similar to `new Error().stack`

This code snippet creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.


This line of code gets a stack trace and prints it:

console.trace();

Source: https://developer.mozilla.org/en-US/docs/Web/API/Console/trace


You can get stack trace by creating error and printing its stack property.

var stackTrace = Error().stack;
print(stackTrace); // if print is available
console.log(stackTrace); // if console.log is available
alert(stackTrace); // ditto
var xhr = new XMLHttpRequest(); xhr.open(...); xhr.send(stackTrace); // submit to server
// or do whatever else with the variable

This unlike console.trace() works in all cases, even if console class is not available in your environment. (Of course, if print is not available, you can use console.log or any other function for printing which you have in your environment).