Sunday, August 19, 2007

Programmatically trigger JavaScript debugger

Debugging JavaScript is not always a fun experience. I recently found a new technique for debugging JavaScipt and while writing this blog entry I was reminded of an better technique. The new technique is the using "debugger" keyword. Just by putting this keyword, not a function, on a new line will call the debugger in IE. Firebug also supports the debugger keyword for debugging in Firefox although you don't really need it as much because of its excellent breakpoint support. The debugger keyword has actually been around for a while I just never knew about it. I found it because I was looking to see if there way to programmatically trigger JavaScript debugger like there the way in C# call Debugger.Break().

function foo()
    // Triggers the debugger

    /* code that I want to debug */

    // These are some ways that I used in the past to trigger the JavaScript debugger
    a.a = 1; // use of undefined variable triggers the debugger
    bar(); // use of undefined function triggers the debugger

The technique that I was reminded of was using the "Script Explorer". This window shows all of the script that is currently loaded into the browser. As easy way to to this is by using the IE View menu > Script Debugger > Open. It is not shown by default even when you are debugging JavaScript but you can access it from the Debug menu > Windows > Script Explorer. Although, Visual Studio 2008 has a new Script Document section of the Solution Explorer that replaces Script Explorer.

If you are an ASP.Net developer you may be addicted to the managed code debugger mainly because it just comes up when you need it.

However debugging JavaScript is a different. First, you have JavaScript debugging turned on through IE's advanced options. This is turned off by default which is a good thing - do you remember how annoying it was when it was the default. What's the problem here? It debugs all websites not just the one you are working on. I haven't hear of a way to just debug the website that is loaded into Visual Studio. If you have JavaScript errors turned off then it is easy to ignore the mounting errors. Considering that both Visual Studio and Internet Explorer are both Microsoft products you think that there would be seamless way to configure IE to debug JavaScript.

As even Scott Gu from Microsoft says "One of the annoying things with VS 2005 is that you have to first run your ASP.Net pages before you can set JavaScript breakpoints in them in the debugger." I have found a much better overall user experience from the most excellent Firefox FireBug extension which it is very easy to set and debug JavaScript right from the browser.