Rocky Singh
Rocky Singh

Reputation: 15420

Check whether console is present

I am writing a plugin. For that I will log a few things, say warnings, necc things, etc. To log them I will use console, but there can be an error if some browser doesn't support console. To handle this error, I am thinking of using this code:

    if (typeof console == 'undefined') console = {};
if (typeof console.log == 'undefined') console.log = function() {};
if (typeof console.debug == 'undefined') console.debug = function() {};
if (typeof console.info == 'undefined') console.info = function() {};
if (typeof console.warn == 'undefined') console.warn = function() {};
if (typeof console.error == 'undefined') console.error = function() {};

Will this work right or is there a better option?

Upvotes: 28

Views: 15113

Answers (5)

Lior
Lior

Reputation: 1608

This approach makes it easier to add/change/remove methods in the future and is more elegant and less redundant than most offered:

if (!"console" in window || typeof console == "undefined") {
    var methods = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    var emptyFn = function () {};
    window.console = {};
    for (var i = 0; i < methods.length; ++i) {
        window.console[methods[i]] = emptyFn;
    }
}

Upvotes: 9

Aravindan R
Aravindan R

Reputation: 3084

How about using a library for logging?

UPDATE: You could use the below script to avoid console errors in browsers that lack a console.

https://github.com/h5bp/html5-boilerplate/blob/master/src/js/plugins.js

Upvotes: 2

Rene Vorndran
Rene Vorndran

Reputation: 723

How about shortening @alexn 's answer a bit

window.console = window.console || { debug: function(){}, log: function() { } };

Upvotes: 0

alexn
alexn

Reputation: 58962

You're approaching it right. You could however shorten it a bit:

if(typeof console === "undefined") {
    console = {
        log: function() { },
        debug: function() { },
        ...
    };
}

This allows you to use console.log/console.debug etc without first checking if a console object is defined. I recommend to always include this snippet if you are logging since it is easy to forget to remove and it will break your site if no console is present.

Upvotes: 34

Arindam
Arindam

Reputation: 342

console && console.log("whatever");

Does this not work ?

Upvotes: 1

Related Questions