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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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;
    }
}

Method 3

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

Does this not work ?

Method 4

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

Method 5

How about shortening @alexn ‘s answer a bit

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x