I was wondering, how can i find out with javascript if the console object is available?
i have the problem that if i forget to remove a debug output
maybe...
if (console) {
// do stuff
}
Defined by firebug, IE8 (need to open the developer tools with F12), Chrome, etc but there is no defined spec for it. There is a console.log wrapper that makes it a very easy to use, cross browser logging solution so if the console doesn't exist your code doesn't explode.
A nice simple and short way of outputting to the console safely is as follows:
window.console && console.log('Debug message');
I always include this in the top of my HTML-header before I load anything else. Debugging with console.debug is just too long for me. And I like to toggle the usage of these console functions.
Don't know how optimized the code is, but it always does the job.
(function() {
var consoleDisabled = false;
if (consoleDisabled) {
window.console = undefined;
}
if (window.console == undefined) {
window.console = {
debug: function() {
return true;
},
info: function() {
return false;
},
warn: function() {
return false;
},
log: function() {
return false;
}
}
}
debug = (function(args) {
window.console.debug(args);
});
info = (function(args) {
window.console.info(args);
});
warn = (function(args) {
window.console.warn(args);
});
log = (function(args) {
window.console.log(args);
});
})();
debug(somevar);
info(somevar);
warn(somevar);
log(somevar);
try{
console.log("test")
}
catch(e){
console={},
console.log=function(a){}
}
just put it at the top of your JS file and then use console.log(); without any worry for browser error, i also had this error in IE9
here's what i use. bear in mind that i am only half-heartedly supporting browsers with no support for console. and i only ever use console.log(), but you can see how it can be extended to support console.dir(), console.info(), etc
var console = console || {
"log": function(stuff) {}
};
I like it because calling it does not cause an error, but it returns [undefined], which i think is appropriate.
Note that many many people before (and after) us have written similar polyfills:
https://gist.github.com/search?q=console+%7C%7C+console