I'm truly stumped by this problem.
I've got some JavaScript to control a product configurator.
A simple bit of code to select some defaults
works fine in Chrome
works fine in IE
doesn't work in Firefox (newest versions of everything)
However, if I do anything to observe the code in FF it works fine.
If I have it alert anything relevant, it works.
If I log anything relevant, it works, but only if the console is actually open so I can see the log. If the console isn't open, doesn't work.
for(type in radio_groups) {
if_checked = !!$(":radio[name="+type+"]:checked").length;
console.log($('.'+type).not('[class*="unavailable"]'));
//This loop doesnt do anything without this log above
alert($('.'+type).not('[class*="unavailable"]'));
// Or this alert.
var t = $('.'+type).not('[class*="unavailable"]');
// Line above doesn't make stuff work.
if(!if_checked)
$('.'+type).not('[class*="unavailable"]').first().click();
}
if_checked is false for every type, I can verify that when it runs.
However, nothing happens.
No buttons are clicked.
This is plain single threaded JS in a browser.
There's no interval/timeout functions on the page.
I can do time arbitrary time consuming tasks before the last line (my best idea was that it was a concurrency issue somehow, I don't see how else logging could affect anything) and it doesn't have any effect.
I can run the same selector and put it in a string, or do anything you can think of to it besides logging or alerting and it wont work; no buttons get clicked. Only actively observing whats happening makes the code work. The entire deal is rather involved and I cant provide the entire thing.
Any ideas on how:
logging can possibly affect the outcome of a simple click event?
why this is Firefox specific? Or other ways I might try to see whats going wrong without the console or alerts?
Edit: Oh, and I've had two other people replicate the issue in their browsers (again, Firefox only), so its not some wonky extension issue unless we all share it.
Thanks.
This line is not valid:
var t = "$('.'+type).not('[class*="unavailable"]')";
It should probably be:
var t = "$('.'+type).not('[class*=\"unavailable\"]')";
or:
var t = $('.'+type).not('[class*="unavailable"]');
Here's a bit of speculation:
if_checked = !!$(":radio[name="+type+"]:checked").length;
It looks like the quotes aren't paired correctly. Did you mean this?
if_checked = !!$(":radio[name='"+type+"']:checked").length;
(See the single quotes that wrap the value of type?)
I've come across this before. If I'm leaving any logging in place in production code I'd wrap it in a try > catch statement.
try {
console.log("my log message")
} catch (err) { };
I know it's considered bad practice to have an empty 'catch' but hey, it's also bad practice to leave the logging in on priduction code.
It seems in FF (also in older IE) if the console is not open then it doesn't exist so the error being caught is probably something like 'console is undefined'
Related
So, since a few days, my chrome developer tools/console won't output any undefined errors or Uncaught ReferenceError in some cases.
The script just stops without any indication, and I don't have pause on exceptions on, and there's no breakpoints.
Trying to call an undefined function foo() for example:
I have the filter on all so I'm not filtering anything.
I've reset the settings via Settings->General->'Restore defaults and reload'
I've tried disabling all extensions, but no difference.
I've tried a new user in chrome, still nothing
I've tried using "use strict" in my code, nothing.
I'm pretty sure this has something to do with reactjs, where foo() is not defined anywhere, but try to call it like the above screenshot. I had the same issue inside mixins.
Strangest thing is, that not all reactClasses have this problem. Also I've been through version 14.x to 14.7.
I've even tried copying a reactClass/Component which does output an error Uncaught ReferenceError as I'm trying in the above screenshot, but just give it another name (ie assign to different variable and export as separate module). And you guessed it, then the above screenshot occurs, no error, For the same exact code ?
I know, you're probably thinking I'm doing something terribly wrong, but how does a copy behave differently?
I think the above image indicates that something very strange is happening here. There must be a logical explanation, but I can't find any.
This is extremely frustrating, and I'm at a loss how to fix this/what the cause is.
It also doesn't matter where I put foo(), whether it's in render or in componentWillMount or any other method. And the worst is, if it's in componentDidMount I don't even notice, except that the component doesn't react or update anymore.
Upon further investigation it seems this problem only occurs on the first render of the whole component hierarchy...
This is new to me, it's as if the initial render has to be flawless and otherwise it will just halt without informing the developer.
On the upside, I now have to pay extra attention to the coherence of my code ;P. But truly, I can't really work like this.
I made a function called test() in javascript file.Placed a simple alert into it.
In html file, called the method on click of a button. But,it was not being invoked.
Problem was in the 11th function, nowhere related to mine !!!! But, how can a person making his first javascript function suppose to find that out ???
I am looking for best ways to debug javascript.
You can debug javascript using many modern browsers. See this question for details on how to debug in Google Chrome:
How do you launch the JavaScript debugger in Google Chrome?
Furthermore, you shouldn't use alert() for debugging as this can give different results to a production version due to alert() causing a pause in the script.
It is best practice to use console.log() and view the output in the browsers Console.
You can also put debugger in your javascript code to force a breakpoint. However I prefer not to use this as forgetting to remove this before deployment will cause your script to pause, which can be quite embarrassing!
You should use the debug console provided by the browser.
Chrome has it inbuilt, press CTRL + SHIFT + j. In Firefox, install Firebug plugin.
In your code, add alert() to show flow and get values of variables.
Also, use console.log() which will only output to the debug console.
Depending on your browser choice there are debugging options - I tend to use Firefox, so Firebug in my case. There is a question that list options for other browsers - What is console.log and how do I use it?
Unless the project you're working on has already adopted a mechanism for debugging, console.log() tends to be a simple and useful option when tracking down a problem.
Whilst debugging you could take the approach to log out a line when entering a function, like so:
var myFunc = function(el) {
console.log('Inside myFunc');
// Existing code
};
This will enable you to see which functions have been called and give you a rough idea of the order of execution.
You can also use console.log() to show the contents of variables - console.log(el);
Be mindful to remove/disable console.log() calls once you're done as it will likely cause some issues in production.
To answer your question within question,
how can a person making his first javascript function suppose to find that out ???
Well, when something is wrong in JavaScript, for example, you made a syntax error - the script will stop working from there. However, this won't stop HTML from rendering on, so it might look as if everything is correct (especially if your JS is not changing the look of the page) but all the functionality of JS will be dead.
That's why we use the debug tools (listed in the other answers here) to see what's wrong, and in cases like this, it's very easy to notice which function has errors and is causing the whole script to break. This would probably have save a few minutes to your seniors as well.
The best approach would be to test frequently so that whenever you run into errors, you can fix them right away.
I am a chronic user of Firebug, and I frequently need to log various stuff so that I can see what I am doing. The console.log function is a lot to type. Even if I assign it to a single letter variable like q = console.log, I have to do it every time I fire up Firebug. Is there any way to do it such that q always refer to console.log (unless, of course, I override it in my session)?
To answer your question, the functionality doesn't currently exist, however I have found the firebug developers to be very responsive in the past. Why don't you put in a feature request on their forum, or better yet, code it up yourself, and ask them to add it?
Depending on your IDE, simply setup a code snippet (I use Flash Develop, so Tools -> Code Snippets).
I believe this to be a better way than setting up redirect scripts and what not, because it stops the Firebug namespace from being polluted, and makes it easier/more consistent to debug if your debugging breaks down.
The screenshot shows me using Flash Develop, hitting Ctrl+B, then hit enter. The pipe (|) in the snippet indicates where the cursor will be placed to start typing after inserting the snippet.
I'd like to write a test case (using Selenium, but not the point of this question) to validate that my web application has no script errors\warnings or unhanded exceptions at certain points in time (like after initializing a major library).
This information can easily be seen in the debug consoles of most browsers. Is it possible to execute a javascript statement to get this information programatically?
It's okay if it's different for each browser, I can deal with that.
not so far read about your issue (as far as I understood your problem) here
The idea be the following:
I found, however, that I was often getting JavaScript errors when the page first loaded (because I was working on the JS and was introducing errors), so I was looking for a quick way to add an assert to my test to check whether any JS errors occurred. After some Googling I came to the conclusion that there is nothing built into Selenium to support this, but there are a number of hacks that can be used to accomplish it. I'm going to describe one of them here. Let me state again, for the record, that this is pretty hacky. I'd love to hear from others who may have better solutions.
I simply add a script to my page that will catch any JS errors by intercepting the window.onerror event:
<script type="text/javascript">
window.onerror=function(msg){
$("body").attr("JSError",msg);
}
</script>
This will cause an attribute called JSError with a value corresponding to the JavaScript error message to be added to the body tag of my document if a JavaScript error occurs. Note that I'm using jQuery to do this, so this specific example won't work if jQuery fails to load. Then, in my Selenium test, I just use the command assertElementNotPresent with a target of //body[#JSError]. Now, if any JavaScript errors occur on the page my test will fail and I'll know I have to address them first. If, for some strange reason, I want to check for a particular JavaScript error, I could use the assertElementPresent command with a target of //body[#JSError='the error message'].
Hope this fresh idea helps you :)
try {
//code
} catch(exception) {
//send ajax request: exception.message, exception.stack, etc.
}
More info - MDN Documentation
I'm working on a new project which has some complex javascript. I can't post any code so that's not what my question is about.
I have a script which works in Firefox 3.0. It was pointed out that the script did not work in Firefox 3.5, so I'm trying to make it work. Indeed the script didn't produce the expected results, so I installed the latest version of Firebug, enabled the console and refreshed the page.
And wow, it worked.
No errors, warnings nothing.
So I disabled the console, and then it didn't work anymore...
What's going on here? The Firebug console somehow changes something in Firefox that makes my script work? Any advice on what next? (besides asking future visitors to install Firebug...)
Could it be something as simple as forgetting to comment a call to console.log() somewhere in your javascript?
If you have hanging references, and the user doesn't have Firebug installed, you're going to get a runtime error that will halt execution of the script.
It sounds to me like there's a chance you have a threading problem, and FireBug is analyzing and possibly slowing down one of the threads so that it has time to complete before the next step is resolved.
Are you possibly utilizing ajax, and something is waiting on that response? Or possibly you're doing something on or after the load of an object that is depending on something else in the DOM?
UPDATE:
For those stumbling upon this now, "threads" in JavaScript really only exist in abstraction (web workers, etc). I was mis-using the term. I was really thinking of an asynchronous action that returned before another one was ready.
Check in your code for console.log(), console.debug().Calling window.console objects methods throws an error if console is undefined (as expected).
In most cases you can easily delete or comment that lines.
I wrote a simple wrapper for firebug (I just use debug but it should give you what you need to duplicate the other methods) that only writes when the console is there so I can use firebug, don't need to go comment out my debug statements and it doesn't break sites for people without it.
If you use this code then use fbconsole.debug instead of console.debug you will never have this problem:
function fbconsole () {
this.debug = function (val) {
if(typeof(console) !== 'undefined' && console != null) {
console.debug(val);
}
}
}
var fbconsole = new fbconsole();