I use Firebug's console.log() for debugging my website. If I try viewing my website in browsers without Firebug then I get a console is not defined error. Is there a way to gracefully avoid this error?
I found this potential solution, but it seems a bit cumbersome. And ideas?
Firebug source code provides a file to do this :
See firebugx.js
Do not reinvent the wheel every day :)
I always create my cross-browser wrappers for console.log alike functions and it looks like this:
function log(a){
try{
console.log(a);
}catch(er){
try{
window.opera.postError(a);
}catch(er){
//no console avaliable. put
//alert(a) here or write to a document node or just ignore
}
}
}
It can be extended for any browsers. in IE when in debug I'd recommend putting this jquery code in last catch:
$('body').append('<pre>'+JSON.serialize(a)+'</pre>');
You must add JSON.serialize to Your script. IE doesn't have it (IE8 might have, I'm not sure)
The linked solution is basically a variant(with a few extra functions) of this:
EDIT The below code doesn't actually work when firefox is present. That'll teach for posting code without checking just to show off my not so 1337 operator ||
skillz:
window.console = window.console || {};
console.log = function(){};
The reason for that is that firefox console is actually a getter only property off window. Hence we can't set it. Instead, something like this needs to be used:
if (!window.console) {
window.console = {};
window.console.log = function(){};
}
Also, console.log
(and console.warn
, console.error
) will work on Webkit browsers, including mobile Safari, pretty cool, huh?
I don't think it gets much better than the workaround you link to. It's of course possible to melt it down to just defining console.log()
and leave off rest, but in essence, you won't get around a construct like this.
Only alternative that comes to mind is checking for console.log every time you call it, and that's even more cumbersome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With