Have you ever got a weird bug in which your Javascript doesn’t work in Internet Explorer but do work in other browsers like Google Chrome or Firefox? Then you go to Internet Explorer, open the Developer Tools (F12), refresh the page and then suddenly everything works again? If this is your case, you may have Javascript code that is making calls to the window.console object and… you should be aware that Internet Explorer lacks a console!
So now what? Well, although I would suggest you not to have calls to console in production code it may be cases for example, in which you have to integrate some library, bear with legacy code or whatever, so yes, there is a workaround for this: define a console fallback if it isn’t available.
To achieve it, add one of the following options at the beginning of your page:
1. Short option, only for console.log
Simple: if the console isn’t defined, define it.
1 2 3 4 5 |
if (!window.console) { console = { log: function() {} }; } |
2. Complete option, for me the best
Usually legacy code doesn’t only use console.log, but other methods like warn, error, info, etc. Then option 1 wouldn’t be enough. Instead use the following script I found at html5-boilerplate, I hope this helps you!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
(function() { var method; var noop = function () {}; var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd','timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn' ]; var length = methods.length; var console = (window.console = window.console || {}); while (length--) { method = methods[length]; // Only stub undefined methods. if (!console[method]) { console[method] = noop; } } }()); |
So if the Javascript doesn’t work in Internet Explorer issue is for you something of the past, you liked this post, you found it useful, or you are simply in a good mood… stay tuned for more and please share it!