I wrote a quick and dirty logger as a jQuery plugin...
(function($){
$.log = function(debug) {
if (console.debug) {
console.debug(debug);
};
};
})(jQuery);
It works fine in Firefox, but in IE7, I'm getting the error...
console.debug is null or not an object
How do I perform a function exists in JavaScript that's patible with IE7?
I wrote a quick and dirty logger as a jQuery plugin...
(function($){
$.log = function(debug) {
if (console.debug) {
console.debug(debug);
};
};
})(jQuery);
It works fine in Firefox, but in IE7, I'm getting the error...
console.debug is null or not an object
How do I perform a function exists in JavaScript that's patible with IE7?
Share Improve this question edited Dec 18, 2012 at 0:14 alex asked Jul 29, 2009 at 5:47 alexalex 491k204 gold badges889 silver badges991 bronze badges4 Answers
Reset to default 4console.debug
is specific to Firebug, which runs under Firefox.
You need to check if window.console
is available before checking for console.log
!
Here's your code reworked with no errors:
(function($){
$.log = function(debug) {
if (window.console && console.debug) {
console.debug(debug);
};
};
})(jQuery);
Check if console is defined, then check if debug is a function:
if (typeof(console) != 'undefined' && typeof(console.debug) == 'function'){
//...
}
$.log = window.console && console.debug ? function(debug) { console.debug(debug); } : function(){};
Variations:
$.log = function( debug ) {
if ( window.console && console.debug ) {
console.debug( debug )
}
}
$.log = function( msg ) {
if ( window.console ) {
if ( console.debug ) console.debug ( msg )
else if ( console.log ) console.log ( msg )
}
}
$.log = function( msg ) {
if ( typeof console === 'object' && typeof console.debug === 'function' ) {
console.debug( msg )
}
}
$.log = 'console' in window && console.debug ? function(m){console.debug(m)}:function(){}
$.log = function() {
if ( 'console' in window ) {
console.debug ? function(m){console.debug(m)} : ( console.log ? function(m){console.log(m)} : function(){}
}
}
$.log = window.log = function(m){ if(window.console && console.debug) console.debug(m) }
The above answers are all correct, but you're going to have the side effect of your log statements being converted from an arguments object into an array, and your output will look (something) like this:
["my", "debug", "statement"]
To fix that you need to forward the arguments object and keep it intact:
$.log = function() { // note no arguments used
if ( window.console && console.debug ) {
console.debug.apply(console, arguments )
}
}
Now the output will look like:
My debug statement