Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 function 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?

like image 601
Anthony Kong Avatar asked May 19 '11 05:05

Anthony Kong


People also ask

What is window in console log?

console. log() restricts your code to work in environments where window is the global object (or a property of the global object).

What is console window in JavaScript?

In JavaScript, the console is an object which provides access to the browser debugging console. We can open a console in web browser by using: Ctrl + Shift + I for windows and Command + Option + K for Mac. The console object provides us with several different methods, like : log() error()

Is the console a window object?

The console object provides access to the browser's debugging console. The console object is a property of the window object.


2 Answers

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.

like image 88
Amadan Avatar answered Sep 19 '22 15:09

Amadan


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).

like image 27
T.J. Crowder Avatar answered Sep 18 '22 15:09

T.J. Crowder