Monday, August 18th, 2008
Getting a JavaScript stracktrace in any browser
Eric Wendelin has posted on getting a JavaScript stack trace no matter that the browser.
With Firebug you can call console.trace()
but what about the rest?
Luke Smith took Eric’s work and added to it, ending up with:
(function () {
YOUR_NAMESPACE.getStackTrace = (function () {
var mode;
try {(0)()} catch (e) {
mode = e.stack ? ‘Firefox’ : window.opera ? ‘Opera’ : ‘Other’;
}
switch (mode) {
case ‘Firefox’ : return function () {
try {(0)()} catch (e) {
return e.stack.replace(/^.*?\n/,”).
replace(/(?:\n@:0)?\s+$/m,”).
replace(/^\(/gm,'{anonymous}(‘).
split(“\n”);
}
};
case ‘Opera’ : return function () {
try {(0)()} catch (e) {
var lines = e.message.split(“\n”),
ANON = ‘{anonymous}’,
lineRE = /Line\s+(\d+).*?in\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i,
i,j,len;
for (i=4,j=0,len=lines.length; i
http://pastie.org/254922 <– this example works.
I’ve formatted the code for read-ability.
I haven’t changed any variable names.