How do I find what Javascript is running on certain events? - javascript

I'll pick Chrome for this example, but I'm open to a solution from any browser.
Use Case:
I have an update button on my website that is used to update item quantities in a shopping cart. I'd like to allow a user to enter a 0 and click update in order to remove the item. Trouble is, there is some listener in some js function that is denying the ability to enter a 0 and click update (after clicking update the old quantity remains).
My question is, what developer tool can I use to find which js function is running during that event? I don't think that Chrome's inspector does this, and I'm not very familiar with Firebug, but I couldn't find the functionality there either.
I feel that I should be able to inspect js firings just like I do css stylings. Is anyone aware of a tool I may use?

I've had to debug some particularly nasty unseen-cause Javascript issues at my job. Knowing the full depth of developer tools like Chrome's is definitely helpful. It undeniably takes some creativity to find places that might be causing the issue, but a few tips:
Tracking down event listeners
Under Chrome's Elements view, try Inspect-ing an element (right-click, Inspect); then, on the right side of the developer view, scroll down to Event Listeners. Here you can view what code files have hooked up an event. Often, this will just point you to a middle-framework from the really devious code you're looking for, but sometimes it will point you in the right direction.
Trapping a DOM modification
Many of the unwanted effects I see are because of something changing some value or attribute on the page that I don't want. Anytime this happens, you can right-click on the element (under the Elements view) and say "Break on..." and the specific scenario you're looking for. When Chrome then hits a breakpoint, you can then look downward in the Stack Trace until you find something recognizable that shouldn't be called.
EDIT after reaching ten votes!
Trapping a JS object modification
If the change you're interested in is code-internal, not in the UI, things get trickier. What's meant by this scenario is that you know somewhere in the code, something incredibly annoying like the following is happening.
company.data.myObject.parameter = undefined;
In this situation, you know myObject is still the same object, but it's being modified, perhaps unintentionally. For that, I often insert the following bit of code, sometimes just through the developer console at some point before said modification happens.
Object.defineProperty(company.data.myObject, 'parameter', {
set: (val) => {
debugger;
}
});
This includes an arrow function - you're only using this for debugging and Chrome supports it, so might as well save keystrokes. What this will do is freeze your debugger as soon as some line of code attempts to modify myObject's "parameter" property. You don't necessarily have to have a global reference to the variable if you can run this line of code from a previous breakpoint that will have the given object in the locals.
Otherwise, if all I'm starting out with is the HTML code, and I want to tie that to Javascript code, I'll often just look for identifying features like "id" elements, and search all JS files in my development directory for it. Normally, I can reach it pretty fast.

Open your page in Firefox with Firebug enabled.
Go to console tab in firebug and click profiling
enter 0 in the textbox and click the button.
Stop profiling.
You will be able to see all the javascript functions which have executed due to your actions. You can view them one by one to figure out which method has caused the mischief.

Go to you code. If you are using jQuery there is going to be a function that will be called with the class or id of that particular update button. Or, if you are using Javascript, there is going to be a function called inside the
<input type="button" name="update" onclick="update()">
These are the two ways to look for the function that is being called; there is no software that I know

Download Firebug for Mozilla Firefox, open it, click on Net and refresh your website. Than, you can see which files are loaded on the page.
If you want to check on errors and what goes wrong with an explanation, than click on console and refresh the page once again. You will see the errors and on which line it goes wrong.
Note: in your console, you can say hold or stop, so that the js file stops loading. And you can edit the script by clicking on script in Firebug. Debugging is simple, as it says on their official page https://getfirebug.com/javascript

Related

What is the fastest way to find a listener for debugging javascript in a browser?

Background:
I often find myself in the position of debugging a piece of Java script on a web page in an unfamiliar codebase, and often one that has seen many developers and coding approaches. Sometimes I do not even what technologies might be in use, eg. angular etc.
The first time I need to address the Java script is when a specific behaviour is unexpected (ie. it has gone wrong.)
Question:
What tool provides the fastest route to identifying the entry point of the code that is causing the problem?
Example:
I have an html element on a page lets say a button. When that button is clicked I expect to see an http request at the server. There are many ways the element can be associated with its Java script listener. eg JQuery, thrid party plugins such as knockout etc, in house scripts, and so on.
Using developer tools I can start debugging this in the browser but only if I already know the entry point to put a breakpoint on.
Is there a faster method to find the entry point than doing regular expressions searches on the pages code based on intuition and guess work to find what might be attached to that particular element?
For me, the best starting point is in Chrome developer tools. You can:
Choose an element in the elements tab
On the right-hand side of the elements tree, click the "Event Listeners" tab.
Find the event you want to debug (like click)
Click the hyperlink to bring up the code for event listeners, and set breakpoints. Sometimes you have to click the "format code" button (looks like { }) to get the code on multiple lines so that the breakpoint is manageable.
Do the click, and you'll hit your breakpoint, allowing you to step through the code, add watch variables, etc.

How to find the place where a certain function is called?

I'm writing a webpage, where I need to do some little changes. The problem is, I need to find the place, where one certain function is called (there are plenty of JavaScript files, so I'm not able to go through them line by line). Do you have any idea, how could I find it out?
I know how to do step-by-step debugging in Firebug or similar browser consoles, but still, I don't know how to recognize the place where the function was called.
I prefer working with consoles in Firefox or Chrome.
Debugging Tips For Chrome:
There are probably a number of ways you can find out where a change is coming from. But I find this one a time saver when it comes to tracking down changes in the DOM. (which will usually lead me to a function I am looking for)
Break on subtree modification or attribute modifications. To do this right click on an element in the DOM tree. Specifically the one you think the change is being applied to. From there you will get a context menu which will give you these options. Selecting either one with set a DOM breakpoint.
If this triggers the debugger you can then proceed to step through the code by using F11 and shift + F11 to skip over functions (useful if you wind up in a library like jQuery). While doing this, pay attention to the call stack. This will tell you where the code is coming from..
More in depth information:
https://developer.chrome.com/devtools/docs/javascript-debugging
To get to know the caller of a function just set a breakpoint at the first line of it. Once the breakpoint gets hit, you can see within the stack trace from where it was called.
Firefox DevTools
Firebug
Chrome DevTools
If you have access to the scripts, you could add at the end of every function you want to watch :
console.trace()
This will output in Chrome's console what function have been called with its position in the file (line number)

Non-breaking breakpoints (trace points) in Javascript?

This is a rather complicated question that may simply be impossible with what's currently available, but if there was an easy way of doing it it would be huge.
I'm debugging some JavaScript in Chrome, and because it's very event-driven, I prefer to get trace reports of the code (what got called, etc.) instead of breakpoints. So wherever I leave a breakpoint, I'd like to see the local function name and arguments.
The closest I can get is to drop a conditional breakpoint in, like the following:
There are two big problems with this approach:
Pasting this into each breakpoint is too cumbersome. People would be far more likely to use it if it could be chosen as the default action for each breakpoint.
In Google Chrome, the log calls get fired twice.
Any ideas on a way to surmount either of these problems? I think it might be possible in IE with VS, but the UI there seems equally cumbersome.
IE11 now has "tracepoints", independent of Visual Studio. They do exactly what you asked for three years ago. I don't see them in Chrome or any other browsers yet, but hopefully they will catch on soon!
The best option I found was to edit the javascript code in Chrome's Javascript panel, adding a console.log.
It would only work after the page has been loaded (unless you can afford to put a break point after refresh and then add the logging lines) and (to be worse) you would have to do it each time you reload the page.
Good luck with your search!
I couldn't find something to do this, so I wrote my own.
Now, instead of constantly inserting and removing console.log calls, I leave the logging in and only watch it when necessary.
Warning: specific code below is untested.
var debug = TraceJS.GetLogger("debug", "mousemove");
$('div').mousemove(function(evt) {
debug(this.id, evt);
});
Every time the mouse is moved over a DIV, it generates a logevent tagged ["mousemove", {id of that element}]
The fun part is being able to selectively watch events. When you want to only see mousemove events for element #a, call the following in the console:
TraceJS('a');
When I want to see all mousemove events, you can call:
TraceJS('mousemove');
Only events that match your filter are shown. If you call TraceJS(no argument), the log calls stop being shown.

javascript debugging - is there a way to tell what functions are being executed?

I'm examining someone else's code and I'm trying to find out what functions are executing when I take certain actions. Is there a way in firebug to do this? (or any other way).
In this particular case I'm trying to find out what happens when I click the 'next' and 'previous' buttons in the editor found at http://trirand.com/blog/jqgrid/jqgrid.html, "Live Data Manipulation >> Navigator" (then clicking the pencil, then the arrows at the bottom).
I've tried grabbing the item I'm clicking and looking at its properties in the console by doing this:
>>> obj = $('#nData')
>>> console.log(obj)
but there doesn't seem to be a handler for click.
What would be wonderful if if there's a way to see what functions are called when I perform an action.
FireQuery may be of some use to you. It hooks into Firebug and displays additional meta-data on all DOM elements which have been modified by JQuery.
You can use Firebug's "Break on next" (the pause looking button in the toolbar)
Then you can the step buttons to move around. Set it to use that, and then click whichever button you want to check the action for.
Since my description probably sucks, check this out.
Edit: This sounds like what you want:
It's primary goal is breaking the Javascript execution at required place in the code that is unknown to the developer beforehand. The typical example, probably well known to most web developers is: "Where in the hell is the code, which is executed if I click this button?".
In firebug, in the Script tab, put a breakpoint in the line you want to inspect. In the right, there is a "Stack" tab where you can see the current stack trace!

Catching the specific Javascript code being executed onClick

I am working on a site that has loads of legacy Javascript and jQuery includes and there is no documentation to show what is happening when.
I have a specific problem to fix and I cannot find the relevant code that is being executed when a button is clicked. To save me from trawling through (and making sense of) hundreds of lines of legacy script, is there a feature, possibly in Firebug, that will identify what script is being executed when I click on a button?
I believe there is a feature in Firebug's console window called Profile. Click profile, click the button, then click profile again. It should give you what all functions were called in that time. Be warned that if this code includes jQuery, you might get a huge long list of functions because jQuery uses tons in its code. Unfortunately, the profiler will also show anonymous functions, which can really be a pain.
Otherwise, do a search in the code for the button's class or ID and go through them. If you have an id of fancy then you might do a search for #fancy in your code and attempt to find it. That may lead you in a general direction, at least.
You can click Firebug's "Break on next" button (in the Script tab; it looks like a pause button), then push the button that you want to debug.
The next time any JavaScript code executes, Firebug will break into the debugger and show you that line of code.
The break button didn't work for me. Instead I did edit the onclick attribute with FireBug and prepended it with "debugger;" ... then you'll break right there once you click :)
None of the above answers worked for me. I am trying to use Firebug to figure out how a feature on a page is working for a site I have no control over. Here is what worked for me.
First, got the id of the element I am clicking on from the page source, and then get a temporary reference to it by creating a watch (under the script tab):
tmp=document.getElementById("idOfElement")
Next, I assigned the current onclick value to another temporary variable.
oldfunc=tmp.onclick
Next, I defined a new onclick function. Initially I tried putting debugger; as the first thing in the function, but this does not work! So instead, I created an alert:
tmp.onclick = function() { alert("Ok"); oldfunc() }
Now, as soon as I click on the button the alert comes up, at which point I then click the "Break on next" button as outlined in another answer to this question. Then I dismiss the alert and immediately I am in the debugger at the correct place.
In my case, the "Break on next" button did not work by itself, because there are a lot of other events, just mousing over the page was causing the breakpoint to be hit, preventing me from ever clicking the button.
In Firebug you can set a breakpoint in some JS and then you get a stack which will let you know the current function call stack. So if you set the breakpoint in function used by several handlers then you can use this to discover exactly which handler you are in.
This probably won't work if you are dealing with AJAX callbacks and the like though.

Categories

Resources