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?
Look for Developer Tools or Simply Tools menu in all major browsers. If you are using Google Chrome the press Cntrl+shift+j to see console. In Firefox, press Ctrl+Shift+I and click on Console to view the console on Firefox. Show activity on this post.
The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console.
Steps to Open the Console Log in Google Chrome By default, the Inspect will open the "Elements" tab in the Developer Tools. Click on the "Console" tab which is to the right of "Elements". Now you can see the Console and any output that has been written to the Console log.
log method, and its friends console. warn and console. error , lets you dump objects in the console. The only difference between these functions is their “type” classification, which looks slightly different and can be filtered when viewing the console output.
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.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With