I'm working in a large project that was developed for several years and had tons of code. Recently uninformative alert start to appear. It just says Undefined. I need to find the source of this alert. Is the any chance to make something like "breakpoint on alert"? I want to see the source of this alert.
One possibility is to redefine alert function. I tried to make it in firefox without any success.
I'd go with redefining window.alert right at the start of the code for this type of development purposes.
window.alert = function(e){ console.warn( "Alerted: " + e ); }
This will give You a line number for sure. ( Tested on chrome console )
This is an old question, but thought I would help out with a simpler solution. A very easy way in Chrome to find the source is by placing a debug in the console on window.alert:
debug(window.alert)
This will break on alert and take you to the source. In general, using console with debug(fname) will break whenever the function fname is called.
As a continuation to Vsevolod's method, in FireBug over Firefox for example, you could place one conditional breakpoint on each and every alert(), and see which one fires off, then go up the callstack shown by FireBug.
The condition could be "typeof whatever_variable_is_displayed == 'undefined'".
Related
I am trying to debug this game I am making. Something is wrong with the for loops and I do not know what it is; essentially I am trying to get my rectangles to spawn on the canvas after the user clicks ready. What are some ways to debug logic errors? Doing this over khanacademy.
When I println the drawRects function. Console says infinite loop and points to my for loops.
When I click ready, the console increases by 1 each time so I know the levelUp function is working.
I cant post another link because not enough rep, but when I println randomRects, nothing appears on the console.
Therefore, I believe it is safe to assume something is wrong with my for loops, because the levelUp function works but the random rectangles are not appearing. What are other debugging techniques I can use to narrow down the problem?
You debug a problem by finding out exactly what the code is doing.
There are a few ways to do that:
Use your head. This is your first line of defense. Run through the code in your head, or better yet with a piece of paper and a pencil. Use some example values for your input, and walk through line by line and see what the code would do. Talk out loud, write stuff down, and do this over and over again. This is a huge part of being a programmer.
Use a console. Processing has a println() function that should go to your JavaScript console in your browser. This is your new best friend. Print out the values of any variables you want to know about, like this:
println("x: " + x);
Or a simple println("here") inside an if statement can tell you whetehr that if statement is executing. Combine this with approach one to really check all of your assumptions.
Use a debugger. If all else fails, step through your code with a debugger. This is basically using a computer to do the first two approaches.
In reality, you'll use a combination of all of the above to debug a problem. But the basic idea is this: you need to understand what your code is doing. You do that by first running through the code in your head or on a piece of paper, and you test any assumptions or anything you aren't sure by printing stuff out.
The below code for opening and closing a window is throwing a java script error 'Member not found'. This does not happen in all machines but for certain users with IE 8.
winobject.blur() in the following code is throwing the error.
var winobject=null;
winobject = window.open('URL','Name',"width=1,height=1,top=2000,left=2000");
if(winobject!=null){
winobject.blur();
self.resizeTo(screen.availWidth,screen.availHeight);
winobject.close();
...
}
Any help or suggestion to resolve this issue?
Some additional observations- This issue only occurs when a window with the 'Name' already exists. Lets say if the user has already closed the pop up window that was already opened then the code will run fine. Also if I add one more window.open under the current one then no exception gets thrown when blur() is invoked. Not sure why though ?
if (typeof winobject != "undefined")
I just had an issue with something like this at work today. give that a try, you should be good to go.
Edit:
I have found the following link which appears to explain what is going on. Because you are creating that window on your own, IE8's "security" is preventing many common actions on it.
My next suggestion as a workaround would be to surround both the winobject.blur() and winobject.close() with if (winobject.blur) and if (winobject.close()) conditionals. Note that you do not have the parenthesis after blur and close in the if's, as you are looking for the presence of the method as opposed to calling the method.
Unfortunately, I'm not sure what the alternatives are that you can use to obtain the same effect. But that should hopefully prevent the error from being thrown.
I'm working on a substantially large rich web page JavaScript application. For some reason a recent change is causing it to randomly hang the browser.
How can I narrow down where the problem is? Since the browser becomes unresponsive, I don't see any errors and can't Break on next using FireBug.
Instead of commenting the hell out of your code, you should use a debug console log.
You should use the console.log() functionality provided by most modern browsers, or emulate it if you use a browser that doesn't support it.
Every time you call console.log('sometext'), a log entry in the debug console of your browser will be created with your specified text, usually followed by the actual time.
You should set a log entry before every critical part of your application flow, then more and more until you find down what log isn't being called. That means the code before that log is hanging the browser.
You can also write your own personal log function with added functionalities, for example the state of some particular variable, or an object containing a more detailed aspect of your program flow, etc.
Example
console.log('step 1');
while(1) {}
console.log('step 2');
The infinite loop will halt the program, but you will still be able to see the console log with the program flow recorded until before the program halted.
So in this example you won't see "step 2" in the console log, but you will see "step 1". This means the program halted between step 1 and step 2.
You can then add additional console log in the code between the two steps to search deeply for the problem, until you find it.
I'm surprised this hasn't been properly answered yet, and the most voted answer is basically "put console logs everywhere until you figure it out" which isn't really a solution, especially with larger applications, unless you really want to spend all your time copy-pasting "console log".
Anyways, all you need is debugger; someone already mentioned this but didn't really explain how it could be used:
In chrome (and most other browsers), debugger; will halt execution, take you to the dev console, and show you the currently executing code on the left and the stack trace on the right. At the top right of the console there are some arrow like buttons. The first one is "resume script execution". The one we want is the next one "step over next function call".
Basically, all you need to do is put a debugger anywhere in your code, at a point where you know the page hasn't frozen yet, and then run it, and repeatedly click "step over next function call" which looks like an arrow jumping over a circle. It will go line by line, call by call, through the execution of your script until it hangs/gets stuck in an infinite loop. At this point, you will be able to see exactly where your code gets stuck, as well as all the variables/values currently in scope, which should help you understand why the script is stuck.
I was just racking my brain trying to find a hanging loop in some rather complex JS I'm working on, and I managed to find it in about 30 seconds using this method.
You can add debugger; anywhere in your JS code to set a breakpoint manually. It will pause execution and allow you to resume/inspect the code (Firebug/FF).
Firebug Wiki page: http://getfirebug.com/wiki/index.php/Debugger;_keyword
Todays browsers Firefox/Seamonkey (Ctrl-Shift-I / Debugger / PAUSE-Icon), Chrome, ... usually have a builtin JS debugger with PAUSE button which works any time. Simply hit that when on a looping / CPU-intensive page, and most likely the "Call Stack" kind of pane will point you to the problem - ready for further inspection ...
To isolate the problem you could start by removing/disabling/commenting different sections of your code until you have narrowed down the code to a small part which will allow you to find the error. Another possibility is to look at your source control check-in history for the different changes that have recently been committed. Hopefully you will understand where the problem comes from.
Install Google Chrome, go to your page, press f12 and the developer console will popup. Then select the Scripts button, then select your script (ex: myScript.js) from the dropdown in the top-left of the console. Then click on the first line (or a line where you think don't hangs) and a break-point will be made. After the javascript reaches your break-point click on one of the buttons of the top-right of the console (you will see a button like Pause symbol and then other 4 button). Press on the 2º button (or the button after pause to step over) or the 3º button (step in). Mouse over the buttons and they will explain to you what they mean.
Then you will go in your code like this until it hangs and then you can debug it better.
Google Chrome debugger is far better than firebug and faster. I made the change from firebug and this is really great! ;)
I know it's primitive, but I like to sprinkle my js code with 'alert's to see how far my code is going before a problem occurs. If alert windows are too annoying, you might setup a textarea to which you can append logs:
<textarea id='txtLog' ...></textarea>
<script>
...
function log(str) {
$('#txtLog').append(str + '\n');
}
log("some message, like 'Executing Step #2'...");
...
</script>
In my experience, issues which cause the browser to become unresponsive are usually infinite loops or the suchlike.
As a start point, investigate your loops for silly things like not incrementing something you later rely on.
As an earlier poster said, other than that, comment out bits of code to isolate the issue. You 'could' use a divide and conquer methodology and near literally comment out half the pages JS, if it worked with a different error, you've probably found the right bit!.
Then split that in half, etc etc until you find the culprit.
I think you can Use Console Log like this
console.log(new Date() + " started Function Name or block of lines from # to #");
// functions or few lines of code
console.log(new Date() + " finished Function Name or block of lines from # to #")
By the end of running your webpage, you can identify the area that take so much time during executions, b
Besides using manual log output and the debugger it might sometimes be helpful to log each and every function call to track down where the loop occurs. Following snippet from Adding console.log to every function automatically might come in handy to do so ...
function augment(withFn) {
var name, fn;
for (name in window) {
fn = window[name];
if (typeof fn === 'function') {
window[name] = (function(name, fn) {
var args = arguments;
return function() {
withFn.apply(this, args);
return fn.apply(this, arguments);
}
})(name, fn);
}
}
}
augment(function(name, fn) {
console.log("calling " + name);
});
I know this question is old, but in VS2013 and you can press the pause button and get a full JS stack trace. This was driving me crazy because the loop was inside angular, so I couldn't really put in alerts, break points, etc. because I had no idea where to put them. I don't know if it works with the free express edition, but it's worth a shot.
I've also read that Chrome has a pause function, so that could be an option, but I haven't tried it myself.
I ran into same problem and that's how I resolved it.
Check Console for errors and fix them
Some time console even is hanging
Check for all the loops if the one is infinite
Check for recursive code
Check for the code which is dynamically adding elements to document
Use break points in your console
Use some console logging i.e log the suspected code blocks
Something I don't really see in these answers is that you can do e.g.:
let start;
let end;
//This would represent your application loop.
while (true) {
start = performance.now();
//Loop code.
//...
end = performance.now();
//Measured in ms.
if (end - start > 1000) {
//Application is lagging! Etc.
}
}
In this manner, you can perhaps detect when your application is starting to perform poorly etc.
https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
I am trying to become better with JavaScript and I have done a great job at breaking a page really badly :)))))
I am trying to use Firebug to debug, but it is a little confusing at first. Which of its tabs is used to debug JavaScript? I see DOM and Script - which should it be?
My general problem is this page:
http://www.comehike.com/outdoors/trees/add_spotted_trees.php?hike_id=108
I made a login for people:
login: test#comehike.com
password: password
What I was trying to do on that page is to get the "clear all" and "clear last" links to work correctly, but I just created a hit mess :)
What happens now is that markers are placed, but after "clear all" the markers aren't recognized and not put into the "rout_markers" id element.
Any clues on how I can get this resolved or at least heading in the right direction?
Much appreciated!
You need to be watching the Console tab for errors and warnings. For instance, you have two I've seen:
On page load:
YUI is not defined
http://www.comehike.com/outdoors/trees/add_spotted_trees.php?hike_id=108
Line 256
After logging in and clicking Remove All Markers:
markers[array_length - 1] is undefined
http://www.comehike.com/outdoors/trees/add_spotted_trees.php?hike_id=108
Line 322
Also, instead of using alert() to test, you can use console.log(), which will print to the console. Just remember to remove these before going live.
In addition, you may want to check out some videos:
http://www.virtuosimedia.com/dev/javascript/15-essential-javascript-video-tutorials
And go through some tutorials:
http://www.softwareishard.com/blog/category/firebug-tutorial/
EDIT
Following my comment, here is what I have done to combat the console.log() conundrum:
try{console.log();}catch(e){var console=new Object;console={log:function(){ininklklaskjdflk=0;}};};
Just to add to what Jared says, using console.log() is a much more efficient way of debugging that alerting everything. However, if you leave this in and visit the page in a browser that doesn't have a console, it will crash. You can just remove the console.log() calls, or if you are worried about forgetting those, you can just use this little piece of code:
if(window.console && console.log) console.log("Log Something");
All that does is check a console exists before sending something to it. If the console doesn't exist, that if statement will evaluate to false, meaning console.log("Log Something") is never run. If you liked you could also write this like so:
if(window.console && console.log) {
console.log("Log Something");
}
Both mean exactly the same thing.
The script pane lets you look at the source of all the javascript running on the page. And you can setup breakpoints and look at variables....
The Console Pane is probably the most useful.
You use it to see errors and console.log statements (from Jack Franklin's Post). You can also run javascript from a "command line" to test it on the page.
My site is suffering from the Operation Aborted error. What I find weird is that in my case the error only sometimes happens. The site has been running fine for three months then today it starts happening but not every time.
The page this is occuring on is rather large with a lot of third party controls. What I'd like is a tool that could pinpoint where the failure is occuring. Seems like the best I can do is find the first javascript error that occurs after the operation aborted; however, this doesn't help much. This failure is because an element of the dom isn't available which I'd expect since IE stopped parsing the HTML.
Any one have any ideas or tricks to narrow this down?
Edit
I appreciate additional ways to resolve the issue; however, what I am looking for is a way to identify which script is causing the issue.
Final Edit
After switching to IE8, I was able to determine the cause was the AjaxControl Toolkit's modal popup dialog. There was no concrete way to determine this which is dissapointing, but the debugger let me see where it was failing which was very consistent. Since there is no way in the control to tell it to move its initialization, I disabled it, and have the script to create the client side control in my document load event handler.
This issue is no fault of the control, it was occuring because the content for the popup is actually in a second form. Frankly I'm surprised it ever worked.
Do you have any javascript that is manipulating the DOM, as the case is described at http://support.microsoft.com/kb/927917#more_information ?
Try moving all script blocks to the very bottom of the page, just before the </body> tag, and don't try to set the innerHTML property of the body tag itself.
If the problem is with javascript executing before the DOM is fully built, try moving any initialization calls into a function that will run only after the page is fully loaded. So, instead of something like this:
<div class="myWidgetControl"/>
<script type="text/javascript">
initializeWidgets();
</script>
Try something like this:
<div class="myWidgetControl"/>
<script type="text/javascript">
$(document).ready(
function () { initializeWidgets(); }
);
</script>
You can use script provided by IE Blog to investigate the problem. See: http://blogs.msdn.com/ie/archive/2009/09/03/preventing-operation-aborted-scenarios.aspx
This is a nifty trick I used (based on the link in the JS comments below) that completely avoids the Op Ab error without affecting performance in other browsers. You first wrap whatever script you're doing that can cause the error (for instance, loading/instantiating a 3rd-party widget) in a function, then call that function within the delayExecutionForIE function -- note that the call to myFunction is in there twice, once for IE and once for nice browsers.
Your 3rd-party script might prevent this working, depending on exactly what it does and how it expects to be loaded, but it's definitely worth a try.
function delayExecutionForIE() {
if ( typeof document.all == "object" &&
(document.readyState != "loaded"
&& document.readyState != "complete")
) {
try {
//If IE is used, use the trick by Diego Perini
//http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
myFunction();
} catch(error) {
setTimeout(delayExecutionForIE, 200);
}
} else {
myFunction();
}
}
function myFunction() {
//this is your function that manipulates the DOM
}
delayExecutionForIE();
in the most cases it is a DOM issue in JS.
$( element ).append( someHtml );
so in IE you can add content to a object only if it has it's closing tag
For example the code below will cause the IE7 to bring the message "Operation aborted"
<div id="o">
...
$(o).appendChild();
...
</div>
And the right way
<div id="o">
...
</div>
$(o).appendChild();
Although IE8 will no longer cause that error to "crash" the rendering entirely, instead logging an error, it is unfortunately not caught by the JavaScript debugger found in the new Developer Tools, and the error message doesn't tell you where the error really occurred.
A workaround, which is certainly tedious, but could locate the issue, is to use IE8's debugger to put a breakpoint on the very first piece of JavaScript code that is run, and then continue hitting the "Step" button until the error icon pops up in the bottom left corner of the browser. When that happens, you know the line of code that causes the error was the one highlighted just before you clicked step. It's likely to be quite a bit of code you'll be stepping through, though, but I can't think of anything else (well, except contacting the vendors of that 3rd party code and seeing if they have any updates that might be related).
Of course, you could just tell your users to upgrade to IE8. ;)
And Microsoft does recommend upgrading to IE8!