Adding console.log() to AIR’s HTMLLoader

Here is a little code snipped I thought I’d post for future reference and may help someone else out.

I was using the HTMLLoader class in Adobe AIR to load content and I came across an error where my Javascript was calling console.log(). In the AIR HTMLLoader environment this function does not exist so I had to come up with a way for it to stop throwing errors.

The solution I came up with was to create the console object and add the log function. That way I could trace out any log info or do anything else with it if I need to. So here is the snipped to add console.log to the HTMLLoader.

[cc lang=”actionscript3″]

/* creating the loader object */
var ldr:HTMLLoader = new HTMLLoader();
ldr.load(new URLRequest(‘path/to/html/file.html’));
ldr.addEventListener(Event.COMPLETE, onLoaded);

/* when load is complete, do the magic */
function onLoaded(e:Event):void
/* Create console object on the window */
ldr.window.console = {};
/* add the log function to the console object, this function could do anything with the log data but here I am just tracing it */
ldr.window.console.log = function(msg){trace(msg)};