Categories
Articles

Using ExternalInterface To Send Messages to Firebug Console

There are times that you do not have the debugger version of Flash Player running when testing in a web browser so you cannot use various extensions and plugins such as Flashbug that will display Actionscript tracing to the browser window. Flashbug is a Firefox Firebug extension.

However you can use the Firebug console window directly from Actionscript using ExternalInterface. In fact you can use it for sending messages to any Javascript console you may have created or use.

ExternalInterface allows you to call Javascript function from within Actionscript. So we can apply it to calling the Firebug console.log method as well.

I have seen other examples of this code on the internet. Most have a few problems with handling errors. The most egregious is not testing if there is a Firebug console available. The problem is that it is easy to overlook removing Firebug console.log statements when you are working in Javascript. The result is errors when viewing the page in a browser like IE or any browser not having Firebug. The same applies to Actionscript calling Javascript functions. A test is needed to verify that the console.log method is available.

Second it the matter of fact inclusion of testing if ExternalInterface is available. ExternalInterface does not support all web browsers. You can check this out on the ExternalInterface documentation page.

This example contains a method you can add to a class in your Flash or Flex classes and call.

[ad name=”Google Adsense”]
Sending a Message To Firebug console.log Method

This log method demonstrates code you might want to use. I gave it two purposes. One to trace to the standard Flash log you see on line 3. The second is to trace to the Firebug console. Putting all of this into one method makes it easy enough to turn off all tracing by commenting out the body of the method. Of course you may want to integrate this into a singleton class and use it throughout your code.

Line 4 insures the browser has ExternalInterface capability available.

Lines 7 to 9 compose a anonymous Javascript function that looks like this:
function(){if (window.console) console.log('Hello World');}

Then line 11 calls the function.

		private function log(message:String):void
		{
			trace (message);
			if (ExternalInterface.available)
			{
				// Create Javascript function to call the Firebug console log method and append the message.
				message = "function(){if (window.console) console.log('" + message;
				// Close the Firebug console log method and the Javascript function.
				message +=  "');}";
				// Request running the function.
				ExternalInterface.call(message);
			}
		}

[ad name=”Google Adsense”]

To use the function, simply call it with your tracing message and you will get the message both in the regular Flash trace consoles you are using and as well in the Firebug console.

log("Hello Firebug Console From Actionscript");