javascript backtrace function


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. /* <![CDATA[ */
  2. function printStackTrace() {
  3. var callstack = [];
  4. var isCallstackPopulated = false;
  5. try {
  6. i.dont.exist+=0; //doesn't exist- that's the point
  7. } catch(e) {
  8. if (e.stack) { //Firefox
  9. var lines = e.stack.split("\n");
  10. for (var i=0, len=lines.length; i<len; i++) {
  11. if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
  12. callstack.push(lines[i]);
  13. }
  14. }
  15. //Remove call to printStackTrace()
  16. callstack.shift();
  17. isCallstackPopulated = true;
  18. }
  19. else if (window.opera && e.message) { //Opera
  20. var lines = e.message.split("\n");
  21. for (var i=0, len=lines.length; i<len; i++) {
  22. if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {
  23. var entry = lines[i];
  24. //Append next line also since it has the file info
  25. if (lines[i+1]) {
  26. entry += " at " + lines[i+1];
  27. i++;
  28. }
  29. callstack.push(entry);
  30. }
  31. }
  32. //Remove call to printStackTrace()
  33. callstack.shift();
  34. isCallstackPopulated = true;
  35. }
  36. }
  37. if (!isCallstackPopulated) { //IE and Safari
  38. var currentFunction = arguments.callee.caller;
  39. while (currentFunction) {
  40. var fn = currentFunction.toString();
  41. var fname = fn.substring(fn.indexOf("function") + 8, fn.indexOf("(")) || "anonymous";
  42. callstack.push(fname);
  43. currentFunction = currentFunction.caller;
  44. }
  45. }
  46. output(callstack);
  47. }
  48.  
  49. function output(arr) {
  50. //Output whatever you want
  51. console.info('stack trace', arr.join("nn"));
  52. }
  53.  
  54. /* ]]> */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.