Difference between console.log enabled verification - javascript

I have seen jquery-ui-1.8.11.js verify console.log functionality by doing
if (this.debug)
console.log()
I have also seen people define an anonymous function that is a no-op for browsers with no console logging like IE7.
if(typeof console === "undefined") {
console = { log: function() { } };
}
Is there a technical difference or are both functionally equivalent?

In the first example you've given, this.debug will be a reference to a debug variable in the jQueryUI code. This debug variable will have been set elsewhere, possibly by checking whether console is defined, but also possibly with other settings.
In any case, the first example is specific to the application; if you want to do a generic check to see whether the console is available, you'll need to use the second technique. You don't have to define an empty console object as per the example, but doing it that way does mean that you won't have to do the if() condition every time you want to call console.log().
Having said all of that, I would counsel you strongly to avoid putting any code into production which contains calls to the console. The console should only be used for debugging purposes while you are working on the code. It should not be necessary in final release, and doing so can be a sign that either your code is unstable or you're unconfident of it, neither of which is a good sign if you're releasing the code for live use.
(libraries such as jQueryUI are an exception to this rule, as they need to provide functionality for developers to do debugging while writing code using their library)

Both of those do something else. The first code suppresses logging messages unless a flag is set. The people who develop jQuery UI need logging when working on it, and turn it on. But people using the library don't want to have their console cluttered by log messages from libraries, so it's off by default. It lets you turn off logging even when the browser supports it – that regular users on IE7 don't get script errors is a (possibly intended) side effect.
The second code defines a dummy console.log(), so you can call the method without checking if it exists everywhere. It will not suppress logging on browsers where it's supported.

The second of the two is standalone, not relying on jQuery. In my opinion, that makes it better.

Related

How to access controls from a console

I tried to execute the following command from the console.
var subject = Xrm.Page.ui.controls.get("subject");
That's the exact syntax I'm using in the web resource that I'm plugging in to CRM. However, I only got an error message saying that "unable to get property 'controls' of undefined or null reference".
I do understand the message. What I want to know is two-fold.
What syntax will work from the console (F12) to refer to the stuff on the screen?
Why doesn't it work the way I did? Where doesn ui come from?
I've checked that I can refer to both Xrm and Crm.Page but apparently ui is null (it's listed when I print out the contents of Page but sett to null).
I know this is a kinda old thread, but if you still getting that 'object doesn't support property..' error when executing the command from console, IE F12; try calling it from the frame i.e
frames[0].Xrm.Page.getAttribute("controlId").getValue();
In CRM 2013 it is a little different
frames[1].Xrm.Page
It's kind of tough to detect the frames across different browsers, so this little javascript can help you out:
for(var i=0;i<5;i++) //loop through 0 to 4
if(frames[i].Xrm.Page.ui != undefined) //check if undefined
{
Xrm = frames[i].Xrm; //assign Xrm
console.info("~: Xrm updated with frame " + i + " :~"); //show info
break; //breakout the loop
}
What it does ?
What it's basically doing is to loop through 0-5 to find frame where
Xrm.Page.ui is not undefined, once it gets it it assigns it to the Xrm and breaks the loop.
How to use ?
To use it just copy/paste and run in the browser console once per
session then after you can run/test all your Xrm codes form the browser console.
This works for me Xrm.Page.getControl("controlId"). It's just a shortcut for what you have already though...cant-disable-set-to-read-only-protect-gray-out-etc-a-field
In addition to what #Daryl said, I can add that I use different syntax. For some reason, I don't get his to work either. Might have to do with different browser version or something. Instead try to execute this, if you still can't get it to work (although I must admit that his is shorter = better).
Xrm.Page.getAttribute("lastname").getValue();
The lastname parts is tested a minute ago on creation of an instance of entity Contact. I just put in a breakpoint inside a script that is executed onchange and while broken-pointed, I entered the command above to the console.
If neither approach works for you, you've got some weird problem with your CRM or browser.
A reason some people need this information is to access their own code. If you need to access your own methods from the console, in 2011, any global methods (or namespaces) in your javascript were also in forms[0]. Obviously, this is a bad idea, just from a naming standpoint. In forms v6+ any global objects or functions are in an object called customScriptsFrame inside frames[0] (or presumably whichever frame the Xrm is found).
frames[0].customScriptsFrame.myFunctionName();

Getting all info on a Javascript variable

I'm not a JavaScript Wizard by a long shot. But I am a web-developer and so I need to know my way around it at least a bit.
Something I'll often do is simply alert a variable to see what it is.
However, the problem is that I'll often get a result like: "object HTMLInputElement". To me this means little to nothing. Sure I can look it up, but I need to alert children() of children() of children(), etc...
I've tried walking through the JavaScript with Firebug, but for some reason this is very slow. Firefox hangs when I start a debug session, for every single debug session and I don't know why.
So, I want to inform if there is a way to get detailed info on variables some other way. Or a system I can use to work with to make things easier.
I find the developer tools in Chrome work quite well, giving a good amount of detail on demand (usually just hovering the mouse over the variable in the script tab; if that variable is a structured object, a little tree control appears and you can drill down). But then, I don't have your Firebug issue either (or at least, not often anymore).
Debugging with alert is very time-wasteful and, as you've found, frustrating; if at all possible I'd look at using a real debugger (like Chrome's Dev Tools; I've also heard good things about Opera's).
This should help:
http://www.openjs.com/scripts/others/dump_function_php_print_r.php
The easiest way to inspect a javascript variable is with a debugger. If Firebug is not working out for you try using Google Chrome, it has an inspector built in.
Btw - not sure what you mean by "start a debug session". If you have firebug installed, you should simply be able to click on the firebug icon on the bottom right of your browser. Go to the script tab, and select from the drop down whatever js file you want, stick in a break point (just left-click on the margin) and refresh the page. I've never had a problem with Firebug, it's always worked extremely well. I strongly advise figuring out whatever your issue with it is, it will make your life a million times easier.
Using any of the browser dev tools, including IE9, you can use console.log to get the variable output on the console. What information this gives you will vary by browser, but with Firebug it allows you to explore the variable in the DOM inspector tab, with full access to all properties and functions (you can even copy the content of a function to paste elsewhere).
For instance:
var foo = {};
// Do lots of stuff with foo
if (typeof(console) !== "undefined" && console.log) { // prevent errors when console not open, ideally all console calls should be removed before going into production
console.log(foo);
}
This has the advantage that it doesn't require any break points, so no slow step-debugging. It won't solve everything though, you'll often still need the debugger.

Stop suppressing JavaScript errors

I'm using Firebug to view JavaScript errors. But I'm also using jQuery. For some reason, I never see JavaScript errors when using jQuery and this is one of the biggest problems with working with jQuery in the first place.
There's no particular code to show, just imagine alert(areareg); where areareg is undefined or any sort of JavaScript error, and Firebug won't tell me about it. The JavaScript will simply fail without warning or notification of any sort. This is always the case, in any project where I've used jQuery and it's the only reason I don't like jQuery; because it's notoriously difficult to debug when something goes wrong.
For some reason I've even had trouble finding this question raised online, let alone answered. But I figured I'd give it a try here:
Is there any way to make jQuery stop suppressing error messages?
Am I the only one in the world who has always had this problem with jQuery?
EDIT:
I use both Firefox (with Firebug) and Chrome, and I only use the non-minified version of jQuery. Still, I have never in my entire life seen a jQuery error message of any kind, neither useful nor useless, nor in fact normal JavaScript errors, when using jQuery.
Well, despite your impression, jQuery itself doesn't do anything to "suppress" error messages. Now, Firefox does tend to throw away certain kinds of exceptions, notably like what you describe. I often find that wrapping a whole Javascript block in a try ... catch with an alert call should an exception happen is a useful way to deal with it, but it's still irritating.
I use google Chrome for my debugging, and it's pretty good, it shows all the jquery errors as well (as Alfred said, if you use minified version, you wont get any meaningful name in your errors, so it's better to use the raw source)
I am having the same problem in FF 18. I am using JSF and JQuery, though it happens even for plain JS code on the page. I intentionally put javascript code that should throw a syntax error without a word in Firebug. FF 18 has its own built-in console that looks similar to firebug. When I disabled the firebug plug-in the console.log messages started showing up. However, the errors are still not showing up. I just tried Chrome and the errors do appear there.
I've run into this problem several times. It's quite inconsistent and hard to replicate, sometimes it seems related to version issues. Settings rarely seem to make a difference, though "Break on next" sometimes (not always) identifies errors that otherwise slip through.
One thing I've noticed is, it tends to happen for code that is triggered inside a callback function, e.g. from a UI event or from an AJAX call. Sometimes Firefox / Firebug will behave like other browsers and show errors in the console, sometimes it gives nothing at all even for incredibly clear-cut cases like:
console.log('something'); // Shows up in console fine
fail // Other browsers give undefined variable error, Firefox gives nothing
console.log('something else'); // Never reached, so silent error clearly happens
The best approach I've found to this is:
Once you've found a no-show error, work back using console.trace() until you reach a point where inside a function, the error is hidden, outside, it shows, adding some code snippet like:
console.trace();
fail // cause the error, look out for a trace followed by nothing
If it's an AJAX call, manually add a basic error handler, because for some reason Firefox/Firebug is losing the default:
$.ajax({
error: function(a,b,c){
throw c;
},
other: '...settings'
}
If it's something you can't add an error handling function to, wrap it in a try... catch, for example:
try {
// whatever the code is within which there are no errors
} catch( err ){
throw err;
}
This should be enough to catch all errors where-ever they are within the scope where Firefox is losing them. Beware of cases where you have a callback within a callback though, you might need to do this twice...

VERY confused - javascript not being executed - unless Console is turned on in Firebug?

I just started doing some Javascript work for a project, I do mostly backend work so I'm sorry for being new at this! Also, not using a Javascript framework because I want to learn about the fundamentals before making everything very easy for myself :)
So, here is my question/confusion: I wrote a little javascript that dynamically changed forms. This is how I called the code:
// loads the initial box
window.onload = initList(environment_box);
// loads artifacts on each change to environment select box
environment_box.onchange = changeList;
This worked like magic - in CHROME that is! I never noticed it wasn't working in Firefox (its just an internal tool, so I can assume decent browsers, but I figure hey, if its working in Chrome, it will work in Firefox!). So, I did some investigation, and it seems as though the code isnt getting executed in Firefox. I whipped out firebug and wanted to see what was going on.
The interesting thing was, when I enabled Console on firebug, my code got executed! I am very confused as to why, and I would much appreciate any help I could get. Thanks!
-Shawn
You are calling some method on console in your JavaScript is my best guess. Chrome has console defined be default, so it is not a problem.
On Firefox, however, there is no such global object (not without Firebug), so when you try to call a property on an undefined object like,
console.log(..);
it throws an exception which you are not catching, so the JavaScript execution halts.
You're probably calling a method of the console object which just doesn't exist by default in most web browsers. It may be always available on webkit based browsers (like Chrome) but with firefox/IE(/opera?) it requires an external add-on, either firebug or a javascript dependency.
Checkout things like firebugx which simply defines the most common methods of a console object as no-op functions.

Javascript best practice: handling Firebug-specific code

Firebug is certainly a wonderful tool for javascript debugging; I use console.log() extensively.
I wanted to know if I can leave the Firebug-specific code in production.
What's the best practice? Commenting the debug code?
If you leave console.log() calls in your production code, then people visiting the site using Internet Explorer will have JavaScript errors. If those people have extra debugging tools configured, then they will see nasty dialog boxes or popups.
A quick search revealed this thread discussing methods to detect if the Firebug console exists: http://www.nabble.com/Re:-detect-firebug-existance-td19610337.html
been bitten by this before. Ideally all the console.log statements need to be removed before production, but this is error prone and developers invariably forget or only test in FF + Firebug.
A possible solution is to create a dummy console object if one isn't already defined.
if( typeof window.console == 'undefined'){
window.console = {
log:function(){}
};
}
One word of caution: It used to be the case for Safari on 10.4 that any call to console.log would throw a security exception as the console object is a reserved object used in the Mac OS Dashboard widgets. Not sure this is the case anymore, will check tonight.
Personally I modified my compressor a while ago to strip out console references pre-compress. A few minutes adding a regex there saves a lifetime of hassle.
Just thought I would add a really good tip for any js debugging.... use the keyword "debugger", and its like a breakpoint in the code, firebug detects it also MSIE (if you have visual studio) detects it and as I say its a breakpoint.
Not many people seem to know about this but I have found it invaluble... also if there isnt a debugger installed on the machine that is running the code, nothing happens and the code goes through fine. Although I wouldn't advise leaving them in there.
I have had many a headache caused by this.
I use console.log() a lot, and until recently, found that it would cause the entire JS code to fail in versions of FF not using firebug.
I usually run a find before going live, and commenting it out.
D
Some compressors will strip out any line prefixed by ;;; (which is a legal sequence to have, being three empty statements.) This way you're not strictly limited to console references (i.e. you could do some calculations and then console.log() the result at the end, and the compressor can strip all of them out.) I use JavaScript::Minifier for this.
I use this in OOP Javascript, making my own wrapper for log that checks that firebug exists:
myclass.prototype.log = function()
{
if( typeof window.console != 'undefined' )
{
console.log.apply( null, arguments );
}
}
Just call:
this.log( arg1, arg2, ...)
Just a reminder that IE Dev Tool does not support apply() on console.log.
Calling console.log.apply() will raise exception in IE8 when dev tool is active.
You can try JavaScript Debug, it is s simple wrapper for console.log
http://benalman.com/projects/javascript-debug-console-log/

Categories

Resources