Console Object on IE

  • Post author:
  • Post category:JavaScript

Here’s the JavaScript you need to avoid console errors in browsers that lack a console. This is taken from HTML5 Boilerplate 4, in plugins.js.

	if (!(window.console && console.log)) {
		(function() {
			var noop = function() {};
			var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
			var length = methods.length;
			var console = window.console = {};
			while (length--) {
				console[methods[length]] = noop;
			}
		}());
	}

If you use jQuery, you can use a more terse version.

	if (!(window.console && console.log)) {
		window.console = {};
		$.each(['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'], function() {
			window.console[this] = $.noop;
		});
	}

If you are only worried about console.log, then you can use

	if (!(window.console && console.log)) {
		window.console = {
			log: function(param) {}
		};
	}