开发者

What is the proper 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 value, is actually initialised to a fu开发者_如何学JAVAnction object ( function log() { [native code] } )

My questions:

  • There is no need to test for the console.log in modern browsers, correct?

  • What is the proper way to initialize has_logger to a boolean value instead of a function object?


If Firebug is not enabled, Firefox will throw an error if you don't check.

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

will always be Boolean.


Yes, that's a perfectly fine way to test, and yes you do have to test. Note that your has_logger variable actually ends up with a reference to the function, so you could turn it into a boolean using the double-bang as Amadan said.

Beware of IE9's odd behavior around console.log, though.

If you want your code to work in other JavaScript environments than browsers, though, you might use this:

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

You can safely test the type of a free reference even if it's not defined. That will work in browsers (where you have window) and other environments (where you don't).


Often times when the console.log functionality doesn't exist in other browsers I still want to output the results somewhere. Instead of having an if statement each time I want to write to the log I've created the following bit of javascript that adds a console.log method to the window object when it doesn't already exist. This means wherever in my code I want to use console.log I can do so without worrying about it breaking in other browsers.

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

Since I use jQuery I use the following to write each message to a div.

$(function () {

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


Firefox 3.6 and earlier does not have a window.console. I don't know that you'd count that as modern.

For your second question, the && operator in JavaScript doesn't return a boolean value; it returns either its left-hand-side expression (if it's falsy) or its right-hand-side expression (if the left-hand-side is not falsy). If you really do want a boolean for some reason, use !!(whatever-value).


All will give you a 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);


Here's what I've come up with lately in an attempt to be really fully bulletproof... I hope you folks will let me know if I've missed something. It seems to guard against reference errors and be false unless log is a function. If someone's attached some other function to window.console.log that throws an error there's just nothing one can do about that.

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 https://stackoverflow.com/a/3390426/1172174

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜