Stuart Lee

Restoring a broken console.log function in Magento30 September 2012

If you've ever developed a site using ecommerce platform Magento, you might have discovered that console.log doesn't work. Some of Magento's built in javascript has hijacked the function and swallows all the output. This can be hugely frustrating if you are trying to debug some javascript code, but luckily there is a clever way to restore the functionality.

The quick version: Use this code (on document ready) and it will start working again.

window.console = jQuery('<iframe>').hide().appendTo('body')[0].contentWindow.console;

The more detailed explanation of what is happening in the above code:

// create a new iframe
var frame = $('<iframe>');

// hide it before adding it to the document so it has no visible effect

// add it, this causes the frame to initialise correctly, and gain it's own window object

// get the base (non-jQuery) element
frame = frame[0];

// get the iframes window object
otherWindow = frame.contentWindow;

// replace this windows console with the other windows console
window.console = otherWindow.console;