Tuesday, July 16, 2013

JavaScript debugging with Firebug’s console logging

As most of us know, Firebug is a great developer assistance tool. In the following short, I discuss how to extend its capabilities even further by using the Firebug console to your JS development advantage.


Firebug - an introduction

Firebug is a Mozilla Firefox add-on and is one of the most powerful and well-known web development tools available for Firefox. It excels at assisting development and backs up any web-app’s development cycle with a plethora of useful sub-tools and features.

Being developer friendly, it provides live HTML modification WRT layout, styles and also control over the page's XHTML, JavaScript, CSS, AJAX requests.

Code inspection and the availability of an excellent JavaScript debugger helps analyze both the network usage as well as chart out performance statistics.

Firebug can be further enhanced using extensions, and provides specific and granular functionalities so as to provide information required.

Although Firebug is a great and opulent contribution, and brims with several features worthy of discussion, we dedicate this write-up to one of its more humble offerings: the console.

Before we start, we assume that the reader has the following installed:

1. Firefox browser

2. Firebug

We also expect you to have knowledge of some basic Firebug usage and its abilities.


Enabling the Firebug console

After installing the Firebug extension and restarting Firefox, Firebug should automatically be running in the background. You can check the same by going to Firefox Menu à Tools à Web Developer à Firebug.

You can launch Firebug by clicking on the Open Firebug entry in this menu, or by pressing function key F12 directly, while having the target webpage open in a Firefox tab. Thereafter, Firebug should open at the bottom of your web page window.


Figure 1: A Firefox session having Firebug enabled

To start using the Firebug features you would need to enable one or more panels in the Firebug window. Panels include the Console, Script, Net and so on. You may need to explicitly click on a panel in order to enable that panel.

Starting to use the Firebug console

For starting off, enable the Firebug console and select the logging level as ‘All’ (refer Figure 1 above). We start with the most basic of all debugging commands, the console.log().

In its simplest form, console.log() takes an argument and writes it to the console tab in Firebug.

The following function provides a simple introduction –

   1: function console_demo() {
   2:  console.log("Calling 
   3: console_demo()!");
   4: }

Listing 1: The above function call will post a log message "Calling console demo()!" at the Firebug console window

Running the above in a Firefox instance leads us to the below output.


Figure 2: The message "Calling console demo()!" being displayed at the Firebug console window.

The above is a basic example of console output. But this is output is only for a Firebug enabled Firefox browser! The function is sure to generate JS errors on non-Firefox browsers. In order to avoid this from happening we need to create a dummy console object and a blank implementation of the log() method.

   1: if (typeof console == 'undefined') {
   2:  var console = 
   3: {};
   4:  console.log = function(msg) 
   5: {
   6:  return;
   8: };
   9: }

Listing 2: The above code creates a dummy console object with a log function for graceful degradation in non-Firefox browsers

Adding the above before any console related debugging will ensure that no JS errors occur on non-Firefox browsers while using the console related functionality.


Functionality offered by the ‘console’ object

In order to aid debugging, Firebug uses the 'console' object, which is loaded for all the browser tabs currently open in Firefox. This object makes available the methods for exposing the actual DOM information and properties.

In addition to the basic logging, the log method also supports formatted log messages like the good old printf.

For example,

   1: console.log("We are nearing %d and today's date is %s.", 2013, new Date());

This will give us the following output –


Figure 3: Message via the console.log displayed in the Firebug console window.

Apart from the basic log method, the console object also provides some more log variants. These are quickly summarized as below –

  • console.debug() – This method logs a message like the console.log method but also provides a line number reference.

  • console.info() – The info() method logs a message with a modified blue "information" icon as well as the referenced line number.

  • console.warn() – This displays the message in a warning format, with yellow background color. This makes highlighting warnings easier during debugging.

  • console.error() – The harbinger of bad news! ‘Error’ displays a custom error message on with a pink background, hence easier to find.

As before, all of the above accept the message parameters (and values if applicable).

The console can also log other DOM Objects and their values. For example, we can use the following console command –

   1: console.log(document.getElementById('AnyElementId'));

This will result in getting a clickable hyperlink which can be clicked to inspect the object further in any of Firebug's HTML, CSS, Script, or DOM tabs.

In addition, Firebug provides assertions which can be used to test the truth value of an expression and to enforce rules; the console object provides some common assert functions like –

  • console.assert(a, "message" [,objects]) - Asserts that an a is true.

  • console.assertEquals(a, b, "message" [,objects]) - Asserts that a is equal to b.

  • console.assertNotEquals(a, b, "message" [,objects]) - Asserts that a is not equal to b.

  • console.assertNull(a, "message" [,objects]) - Asserts that a is equal to null.

Many more asserts are provided for comparison and instance checking.


Using console for information tracing and profiling JavaScript

The console’s features of script-enabled logging enable JS profiling and measuring the perceptible aspects of the code.

Stack tracing via console.trace() – This method is useful in showing the current stack trace at its point of invocation. This informative stack trace tells us about the functions on the stack and if applicable, also the values of each of the arguments passed to the function.

JavaScript performance – A simple approach would involve the use of console.time The console.time("name") method is used to start a timer with an id (name). This is to be called just before the code whose running time is to be evaluated.

Afterwards, we call the console.timeEnd("name") to stop the above started timer and log the elapsed milliseconds, logged by Firebug as the time spent in between the two events.

A more thorough approach would be to use the console.profile(). This is called just before the code to be evaluated. To end profiling, simply call console.profileEnd() afterwards.

Firebug will create a detailed report about the various function related statistics.

We can also make use of the simple console.count("name") which effectively logs the total times a function or line of code gets executed.

Conclusion & follow up

The above is an introduction to the logging possibilities brought forth by Firebug. There are many more ways of getting the best out of logging via the Firebug console.

For example, both console.dir(object) (which creates an interactive listing of an object's properties) and console.dirxml(element) (which prints an XML outline of the entire element structure) can be used easily to get hold of object properties, be it for a single object or for all the elements in an HTML fragment.

NOTE: The above post is taken from the “Logging JS with Firebug” article which featured in “JSMag December 2012”. This article was collaborated by Chetan Khurana & Chandan Luthra.

Replicated here for all my friends and anyone who needs to know!

Post a Comment