Debugging for AJAX applications
From TroubleshootingWiki
| Official Page |
| Project Documentation |
| Download |
|
Developing AJAX applications that involve complex client-side programming and communication with the server side raises the need for equally complex debugging tools and techniques.
Most of today's AJAX frameworks, including the Microsoft AJAX Library, offer built-in capabilities for debugging and tracing. In this tutorial we will learn about the capabilities built in the Microsoft AJAX Library, and we'll also learn about third-party debugging and tracing tools.
More specifically, you will:
- Learn about the debugging and tracing capabilities of Microsoft AJAX Library
- Learn how to enable and use Internet Explorer's debugging capabilities
- Work with Web Development Helper, Developer Toolbar, and other Internet Explorer tools
- Work with Firefox plugins such as FireBug, Venkman JavaScript Debugger, and Web Developer
- Use Fiddler to analyze the traffic between the web server and your web client
Contents |
[edit] AJAX Debugging Overview
Unfortunately, today's tools for client-side debugging and tracing aren't as evolved as their server-side counterparts. For example, things such as capturing ongoing communication traffic between the client and the server, or client-side debugging, aren't usually supported by today's IDEs (Integrated Development Environments) such as Microsoft Visual Studio 2005. The next version of Visual Studio (code-named Orcas at the time of writing) promises a lot of improvements in this area:
- Improved IntelliSense technology with support for JavaScript code, which provides coding hints based on specially-formatted comments in the code
- Breakpoints in inline JavaScript code
These are only the most important new coming features; there are others as well. For more information we suggest that you browse and keep an eye on Scott Guthrie's blog at http://weblogs.asp.net/scottgu/, the JScript blog at http://blogs.msdn.com/jscript/, Bertrand Le Roy's blog at http://weblogs.asp.net/bleroy.
Until this new edition of Visual Studio is released, we can rely on third-party tools that can do a very good job at helping us develop our AJAX applications. As you found out earlier, you'll meet a number of tools for Internet Explorer and Mozilla Firefox.
[edit] Debugging and Tracing with Microsoft AJAX Library
The common practices for debugging JavaScript code are:
- Putting alert messages throughout the code to get notified about the values of the variables
- Logging tracing messages in a
<div>element
While the first option is straightforward, the second option offers a centralized place for storing different messages and could be considered more appropriate. Nevertheless both options can come in quite handy depending on the circumstances.
Microsoft AJAX Library offers the Sys.Debug object that has a series of methods that you can use for debugging and tracing. The diagram of this class is presented in Figure 8-1.
As we can easily see in the diagram, Sys.Debug offers the most common features that we can find also in other languages: assert(), trace(), traceDump(), fail(), and clearTrace().
assert(), trace(), and fail() automatically send the messages to the debugging console of the browser. To see the messages in IE you need to have the Web Development Helper, and for Firefox you need the FireBug plugin. Both of these tools are presented later in this tutorial. Internally assert() calls fail() if the expression evaluates to false. fail() simply logs the message passed in by assert to the debugging console.
trace() offers an interesting feature beside logging to the debugging console: it offers the possibility to log the trace message in a <textarea> element with the ID TraceConsole. If such an element is found, trace() will log this message in this element too.
The clearTrace() function simply clears the <TraceConsole> element, if found.
The traceDump() function traces all the information about an object including its properties. Internally this function uses the trace() function so that we can have the information logged in the browser's debugging console, and in the <TraceConsole> element (if it exists).
[edit] MicrosoftAjax.debug.js
You might have wondered why the Microsoft AJAX Library comes with both release and debug version of the JavaScript file. The major features of the debug version of the library files are:
- The script is nicely formatted
- The names of variables are not obfuscated
- The script contains code comments
- Some of the functions have the optional summary data that will be used by Visual Studio "Orcas" for code auto-completion
- The script outputs debugging-friendly information
- Parameters are validated
Once the development stage is finished, you can switch your application to the release version of the script (MicrosoftAjax.js), which is smaller and doesn't contain the debugging features presented above.
Perhaps the most interesting features of the debug version are the last two: debugging-friendly information and parameter validation.
[edit] Anonymous Functions vs. Pseudo-Named Functions
We will explain these two concepts by taking a look at how different functions are defined in the debug and release version of the library. The debug version of the library contains:
function Sys$_Debug$assert(condition, message, displayCaller) {
...
}
Sys._Debug.prototype = {
assert: Sys$_Debug$assert,
...
}
and:
String.format = function String$format(format, args) {...}
In the release version of the library we have:
Sys._Debug.prototype = {
assert: function(c, a, b) {
...
}
and:
String.format = function() {...}
In the release version, we have methods that are anonymous functions. This means that within a debugger stack trace the method name will read JScript anonymous function (as shown in Figure 8-2). This is not very useful for debugging purposes, is it?
However, the debug version of the library uses the dollar-syntax to provide alias names for our functions: String$format() for String.format() and Sys$Debug$assert() for Sys.Debug.assert(). When using the debug version of the file, the stack trace would look like Figure 8-3.
We can still notice some anonymous functions as they are the result of creating callback or delegate functions. The example shows two different ways of coding:
- In the debug version, the function is declared outside the prototype and then referenced in the prototype declaration.
- In the release version, the declaration is done directly where the function is declared (outside or inside the prototype).
[edit] Parameters Validation
Another interesting feature that has not been documented in the Microsoft AJAX Library documentation is that of parameters validation.
Type safety is one of the typical problems when it comes to using JavaScript. Although the dynamic type features are really useful, sometimes we might really want to make sure that a parameter or object is of a certain type. To check the data type of an object, you can try converting the object to the desired type, or using the methods defined by Type. Fortunately the Microsoft AJAX Library has a function that does the dirty work for us: Function._validateParams(). The class diagram in Figure 8-4 shows the _validateParameter() and _validateParams() methods of the Function class.
The Function._validateParams() function, even if it is declared as private (by convention, using the leading underscore), can be used by our scripts as it is used throughout the debug version of the Microsoft AJAX Library. Here's an example of using this function:
function Sys$_Debug$fail(message) {
/// <param name="message" type="String" mayBeNull="true"></param>
var e = Function._validateParams(arguments,
[ {name: "message", type: String, mayBeNull: true} ]);
if (e) throw e;
This shows how the parameter for the fail() function is validated as a String. We can also see the additional code comments inside the function, which are meant to be used by the IntelliSense feature in Visual Studio "Orcas" to check for the correctness of the parameter types.
While the first parameter of _validateParams() represents an array of parameters to be checked, the second parameter is an array of JSON objects describing the validation rules for the array of parameters. Each JSON object contains a validation rule for a parameter. The JSON object is a dictionary of keys and values. The list of keys that can be used is described in the table that follows.
| Key | Description |
|---|---|
name
| The name of the parameter |
type
| The allowed type for this parameter (ex: String, Array, Function,
|
mayBeNull
| Boolean value indicating whether this parameter can be passed as null or not
|
domElement
| Boolean value indicating whether this parameter is a DOM element or not |
integer
| Boolean value indicating whether this parameter should have an integer value or not |
optional
| Boolean value indicating whether this parameter is optional or not |
parameterArray
| Boolean value indicating whether this parameter should be an Array or not
|
elementType
| The allowed type for each element of an array (type must be Array)
|
elementMayBeNull
| Boolean value indicating whether an array element could have null or not (type must be
|
elementDomElement
| Boolean value indicating whether each element of an array is a DOM element (type must be Array)
|
elementInteger
| Boolean value indicating whether each element of an array should have an integer value (type must be
|
The function returns an error message if the parameters don't validate and the error is typically thrown like this:
if (e) throw e;
This exception could be caught and the appropriate measures taken programmatically. If the exception is not caught, the error will pop up in the debugging console of the browser.
[edit] Debugging in Internet Explorer
By default, JavaScript errors are ignored by Internet Explorer. In order to be able to debug in Internet Explorer, you need to:
- Start Internet Explorer and go to Tools | Internet Options | Advanced and clear the Disable script debugging (Internet Explorer) and Disable script debugging (Other) checkboxes. If you want a pop-up window to be displayed for each error, you need to check the Display a notification about every script error checkbox, as shown in Figure 8-5.
- Open the solution you want to debug in Visual Studio.
- Execute the project.
- After the Internet Explorer window opens, go back to Visual Studio.
- Open the script explorer by going to Debug | Windows | Script Explorer. The script explorer will list the available script files that can be debugged (see Figure 8-6).
- Double-clicking a file in the script explorer will open it in the editor. There you can place breakpoints inside JavaScript files, and the feature will work just as it does when debugging server-side code. Figure 8-7 shows Visual Studio.
Alternatively, if you have Visual Studio, you can attach the debugger to an existing the Internet Explorer process by selecting Debug | Attach to Process, and then choosing the Internet Explorer process (iexplore.exe).
If Internet Explorer is configured for debugging and a script error is encounted in the browser while no debugger is attached, you're promoted to choose one of the available debuggers:
- Visual Studio and Visual Web Developer 2005
- Microsoft Script Debugger (downloadable from Microsoft's website)
- Microsoft Script Editor (ships with Microsoft Office)
For more about debugging web applications in Visual Studio, see these links:
- http://msdn2.microsoft.com/en-us/library/sc65sadd(VS.80).aspx
- http://www.developerfusion.co.uk/show/5918/
- http://msdn2.microsoft.com/en-us/library/k2h50zzs(VS.80).aspx
[edit] Web Development Helper
Web Development Helper is a great tool developed by Nikhil Kothari and should be used by every developer who needs the following development features:
- HTTP(S) traffic monitoring
- DOM inspector
- Script errors and immediate window
Web Development Helper can be downloaded from: http://www.nikhilk.net/Project.WebDevHelper.aspx.
For more documentation about this tool, check the following links:
- http://projects.nikhilk.net/WebDevHelper/Readme.pdf
- http://www.nikhilk.net/WebDevHelperDebuggingTools.aspx
- http://weblogs.asp.net/scottgu/archive/2006/11/13/Nikhil_2700_s-WebDevHelper-Utility-and-ASP.NET-AJAX-Support.aspx
When it comes to debugging, the tool offers nice features such as showing the trace, catching run-time errors, and showing the full call stack (including script URL, line number, and line of code). The Script Console window allows entering custom script that is executed within the document context.
[edit] Internet Explorer Developer Toolbar
Microsoft offers the Internet Explorer Developer toolbar as an option for exploring web pages. It is especially useful for working with the page's DOM element, CSS styles, cookies, etc. It can be downloaded Microsoft's website..After it installs, you open it through Tools | Toolbars | Explorer Bar | IE Developer Toolbar.
It is worth mentioning that it doesn't compete with Nikhil's tool, but it's more like a complementary tool as it doesn't offer JavaScript debugging capabilities or any of the other main features by Web Development Helper.
[edit] Other tools
There are other other tools that are worth mentioning and that you should keep an eye on:
- Damian Meher's TraceJS is a tool that logs every line of script executed in Internet Explorer. Find it at http://damianblog.com/2006/11/23/tracejs/.
- Julien Couvreur's XMLHttpRequest debugging bookmarklet. See http://blog.monstuff.com/archives/000291.html and [http://weblogs.asp.net/bleroy/archive/2006/05 /15/446532.aspx http://weblogs.asp.net/bleroy/archive/2006/05/15/446532.aspx].
[edit] Debugging in Firefox
With the increasing number of users of Firefox, the number of tools used for web development has grown as well.
First of all, Firefox offers an Error Console accessible from the Tools menu, where all the JavaScript errors, warnings, and messages are logged. It also has a built-in script evaluator within the document context, and the DOM Inspector tool, which can be selected at installation time, so we can say that the features packaged into Firefox are quite advanced in comparison with the default features of Internet Explorer. Figure 8-9 shows the Error Console signalling a typo in our code.
[edit] Firebug
Firebug (http://www.getfirebug.com/) is a Firefox plugin that offers almost anything a web developer could want from a debugging tool:
- Debugging and profiling script
- Monitoring HTTP traffic
- Examining HTTP headers
- Inspecting and editing the DOM
- Inspecting and editing CSS
- Quick search for filtering errors and messages
Delivering such a powerful set of tools in one free product makes Firebug the perfect choice for debugging applications in Firefox. Figure 8-10 shows Firebug in action.
===Venkman JavaScript Debugger===
The Venkman JavaScript debugger (http://www.mozilla.org/projects/venkman/) is a powerful tool for debugging in Mozilla-based browsers (Firefox, Netscape, and Seamonkey).
Like Firebug, Venkman JavaScript Debugger offers debugging and profiling, full call stack, breakpoints, local variables, and watches, all within an interface that is very similar to Visual Studio. Figure 8-11 shows this tool in action.
You can find a few excellent online articles for using Venkman JavaScript Debugger:
- http://www.svendtofte.com/code/learning_venkman/
- http://www.hacksrus.com/~ginda/venkman/
- http://www.webreference.com/programming/javascript/venkman/
[edit] Web Developer
Similar to what Firebug and Internet Explorer Developer Toolbar offer, Web Developer plugin (https://addons.mozilla.org/en-US/firefox/addon/60), provides a most comprehensive set of tools for:
- DOM information and inspection
- Outlining different elements (frames, headings, tables, links, etc.)
- HTTP headers, JavaScript, images information
- Cookies
- CSS
- Page validation (CSS, HTML, WAI, links, Section 508)
All in all, this extension is a very good companion for developing websites. The homepage for this extension and some documentation can be found at http://chrispederick.com/work/webdeveloper/.
[edit] Fiddler
When it comes to inspecting and tampering with the HTTP(S) traffic from our computer and the Internet, the most popular tool you can find is Fiddler. This is a freeware tool that allows inspecting all HTTP and HTTPS traffic and tampering it, setting breakpoints, making it an ideal candidate for debugging applications.
It also offers an event-based subscription system offering the capability to easily extend it. Install Fiddler from http://www.fiddler2.com/Fiddler2/. You can find a quick introduction to Fiddler on MSDN, and in the following resources:
- Fiddler tutorial http://www.developer.com/lang/jscript/article.php/3631066
- Fiddler2 demonstration videos http://www.fiddler2.com/fiddler/help/video/default.asp
- Fiddler2 extensions development http://www.fiddlertool.com/fiddler2/extensions.asp
- Fiddler2 user interface http://www.fiddler2.com/Fiddler/help/ui.asp
[edit] Testing
There are a lot of testing tools available today, but only few of them allow for automatic testing of AJAX applications. Dan Wahlin has put together a list of automated testing and debugging tools on his weblog at http://weblogs.asp.net/dwahlin/ on 2007/02/16/.
In his article we can find some of the tools that we presented so far, and also a comprehensive list of tools that we can use for automatic testing.
A less documented feature of Fiddler is that it can generate Visual Studio WebTest files that can be using in Visual Studio. Why is this necessary? Visual Studio doesn't record AJAX requests based on XMLHttpRequest, but only full postbacks.
In order to create a Visual Studio WebTest file, you need to follow these steps:
- Open Fiddler.
- Start capturing the traffic by pressing F12 or by selecting File | Capture Traffic.
- Browse the AJAX application and Fiddler will register the requests.
- After having finished the steps save the session by going to File' | Save | Session(s) | as Visual Studio Web Test.
- Now you can import the generated file in Visual Studio and use it for automatic testing.
[edit] Source
The source of this content is Chapter 8: Debugging Tools and Techniques of Microsoft AJAX Library Essentials by Cristian Darie, Bogdan Brinzarea (Packt Publishing, 2007).

