Missing console on browsers
December 5, 2011 console Internet Explorer javascript webdevelopment
Recently, I was building a website for a customer. The project is built in JSP, depending heavily on jQuery and jQueryMobile, and running on JBoss. The website is a front-end for a Smallworld application written in Magik, using GSS as a connector exposing business services via HTTP/XML.
As usual, several people wanted to check out the progress during development (and they should, but that is another story) and use the website to demo it to other customers. So I deployed a new version of the website to the JBoss server and happily went on coding. Mind you, the website was still in development and had debug/trace-statements in the code.
After a while, I was contacted by the customer. The customer stated that a part of the functionality was not working properly. After hearing out the customer and trying to repeat his actions, I was able to reproduce it. But only using Internet Explorer. I never got the error, as I’m using mostly Chrome.
A debugging fest started and soon the problematic code was located. The code itself was doing some AJAX calls, but was also using the global variable console to print out trace-statements, such as:
...
console.log('multitap_send_update#Starting AJAX call');
...
Investigating further, the console variable was not holding any reference to an object. Alas, calling a method on that object resulted in a failure and code-executing stopped unexpectedly. After a short Google-session I found this link. Unfortunately, the solution did not seem to work.
To circumvent the problem I crafted some code to fix the problem myself:
function NullConsole() {
}
NullConsole.prototype.log = function() { };
NullConsole.prototype.info = function() { };
NullConsole.prototype.warn = function() { };
NullConsole.prototype.error = function() { };
NullConsole.prototype.assert = function() { };
NullConsole.prototype.dir = function() { };
NullConsole.prototype.clear = function() { };
NullConsole.prototype.profile = function() { };
NullConsole.prototype.profileEnd = function() { };
function fixIeConsoleMadness() {
if (!window.console) {
window.console = new NullConsole();
}
}
Probably not the most elegant solutions, but it works.
It is not possible to check if the variable console is null
as the compiler will give a variable undefined
error (although, this would work: typeof console
.) Fortunately, in most (if not all) browsers, the contents of the variable window is mapped to the global namespace. I.e., when a global variable is created, it is added to the window object/variable.
A new NullConsole object is created, emulating the “real” console. Now when some code wants to use the console, it actually performs the call on the NullConsole and nothing happens, instead of breaking.
Thus, the problem was fixed and the customer could happily see the progress on the website.