robjmills
robjmills

Reputation: 18598

Preventing console errors

Whats the best approach for preventing errors when console.log calls have been left in JavaScript and it is executed on Browsers without a console or with console deactivated. Is there a way it can be automatically overridden to become a javascript alert for example?

Upvotes: 5

Views: 1939

Answers (3)

sje397
sje397

Reputation: 41822

if(!window.console) console = {log: function(s) {alert(s);}};

You can of course add more of the functions that console normally has.

Upvotes: 4

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827366

You have to check if the console identifier is available, you can do it either by using the typeof operator, or by checking window.console, because if you access directly an identifier and it's not defined, you will get a ReferenceError.

For example:

if (typeof console == "undefined") {
  window.console = {
    log: function () {
      // do nothing
    }
  };
  console.warn = console.debug = console.log;
} 

Upvotes: 3

Andy Robinson
Andy Robinson

Reputation: 7429

Here's what I use :-

if(typeof(console) != "undefined")

Upvotes: 0

Related Questions