Debugging JavaScript with log entries

(Those who don't read this site for the nerdy programming stuff can look away... now.)

Most of the time, firing up Venkman to figure out whether some JavaScript code block is getting triggered or not is overkill. But using alert() calls quickly gets annoying if your code block may be triggering a lot.

There's a few ways to log information from JavaScript less obtrusively in Firefox. My preferred way is to use the Firefox console. Not the JavaScript console, which seems to be out of bounds, but the browser console.

To get things working, you need to join a few dots:

  • Start Firefox like so: firefox.exe -console
  • In about:config, right-click to bring up the context menu
  • Choose New->Boolean
  • When prompted for the preference name, enter:
  • When prompted for the boolean value, choose True

You've just enabled logging to the console window. So how do you log to this console from JavaScript? You use dump(), like so:

dump("hello world\n");

This works well in Firefox, where dump() is a system function. To play nicely with other browsers, you probably want to create a wrapper function.

In this example, clog() (for console log, but name it what you will) is my wrapper for dump():

function clog(msg) {
  if (typeof(dump) != 'undefined'){dump(msg +"\n");}

clog("hello world");

It simply checks whether the function is available: if it is, it gets used. Otherwise, nothing happens. Couldn't be simpler.

Let me know how you go in the comments.

Joseph | 24 Oct 2005

Sorry, comments are not available on this post.

stuff & nonsense

  • Topographic viewTopographic view
     shows elements on a webpage according to how deeply nested they are. It's a bookmarklet for web development.
  • The qualifierThe qualifier
     renders controversial statements on this page harmless. Reinstate the slings and barbs by refreshing. Also a bookmarklet.

  • jjmap
    American Diary

    Two weeks with the apple and the lone star (illustrated).

all posts, ordered by month in reverse-chronological order:

In Words

In Other Words