What is the correct way to detect the presence of window.console?

I have this bit of code:

            var has_logger = (window.console && window.console.log);
            if (has_logger) {
                window.console.log(data);
            }

has_logger, instead of being a boolean, is actually initialized to the function object ( function log() { [native code] })

My questions:

  • No need to test for console.log in modern browsers, right?

  • What is the correct initialization method has_loggerfor a boolean value instead of a function object?

+5
source share
6 answers

If Firebug is not enabled, Firefox throws an error if you do not check.

var has_logger = !!(window.console && window.console.log);

will always be boolean.

+4
source

, , , . , has_logger , , .

IE9 console.log.

, JavaScript, , :

has_logger = typeof console === "object" && console.log;

, . ( window) ( ).

+4

, console.log , -. if , , javascript, console.log window, . , , console.log, , , .

(function () {
        if (typeof window.console !== "object")
            window.console = {
                log: function (message) {
                    // Write the message somewhere in browsers that don't support console.log
                }
            };
    } ());

jQuery, div.

$(function () {

    (function () {
        if (typeof window.console !== "object")
            window.console = {
                log: function (message) {
                    $('<div>' + message + '</div>').appendTo('#consoleArea');
                }
            };
        } ());
});
+3

Firefox 3.6 window.console. , .

&& JavaScript ; ( ), ( ). - , !!(whatever-value).

+2

bool:

var has_logger = (window.console && window.console.log) ? true : false;
var has_logger = new Boolean(window.console && window.console.log);
var has_logger = !!(window.console && window.console.log);
+2

, , ... , , , , - . , , log . - - window.console.log, , .

var hasLog = !!("console" in window && 
                window.console && 
                "log" in window.console && 
                window.console.log && 
                typeof window.console.log == 'function')

I came up with this after reading fooobar.com/questions/672 / ...

+1
source

All Articles