Tuesday, 7 August 2007

Javascript debugging, an alternative to alert()

This is a simple trick to provide a more flexible approach for displaying debugging output when working on javascript code in your APEX applications. It uses a couple of debugging javascript functions, print() and println() which will show your debug messages in the current page's footer. This allows for multiple messages to be output without having to click through each one, as is necessary with the alert() function. With other benefits too such as being able to copy the text output which is not possible with alert().

1. First add the following line to your 'Page Template > Definition > Footer', at the beginning:
<div id="debug"></div>
(It doesn't really matter where this goes in the 'Footer' code, as long as it's before the closing </body> tag.)

2. Then we need to make the following two javascript functions available for use in your application. (The recommended approach would be to store them in a '.js' file and place this file on your web server.)
//print output messages to your page
function print(p_value){
$x("debug").innerHTML = $x("debug").innerHTML +
//print output messages to your page with a line break
function println(p_value){
$x("debug").innerHTML = $x("debug").innerHTML +
p_value + '<br/>';

3. You can then call either print() or println() from within your javascript code.

Happy debugging!

Do you Firebug? Then there is a simpler way!

If you use Firefox with Firebug, then another way of debugging is to use the built-in Console API. This details some very useful calls such as:

console.log - Writes a message to the Firebug console

console.trace - Writes an interactive stack trace to the Firebug console with information about the calling function and also the parameters passed to the function. It is interactive in the sense that you can click the function name to take you straight to the function source, very nice!

This API provides more calls as well which look very useful, so it's worth taking a look.

(Thank you Carl!)


Carl Backstrom said...

Nice example.

I recommend using Firebug rather than writing your own debugs http://www.getfirebug.com/

It has a calls like console.log() and console.alert() that are very powerful.

we used to use something like that in APEX development. We actually had a textarea and just concatenated error messages into it

function cDebug(text){$x('debug').value+=text;}

The c in cDebug meaning Carl of course :) There is actually still an empty cDebug in our library so if anyone else used to call it it doesn't error out.

Anthony Rayner said...


Thank you!

I've updated my post with a little section on this very cool Firebug feature. I have used Firebug a bit in the past, but was not aware of the console API! Very nice.