JavaScript - Debugging in Chrome
Most developers know how to use the browser's dev tools to set breakpoints in JavaScript. But how do you debug a function when you do not know where it is called?
Keyword "debugger"
A known keyword in JavaScript is debugger
.
If a script contains this keyword and the browser's dev tools are open, it will stop at that point.
(More details on W3Schools)
Example:
function myFunc() {
// ...
debugger;
// ...
}
"debug" and "undebug"
In Chrome-based browsers, there are lesser-known features built into the JavaScript console that help with debugging.
The function debug()
can be used to set a breakpoint on a function where we do not know its location in the source code.
// Somewhere in the source code:
function myFunc() { ... }
// In the browser console:
> debug(myFunc)
// A function of an object:
> debug(myObject.myFunc)
// If "myFunc" is called the next time, the debugger will
// stop at the first instruction inside this function.
// Remove the breakpoint with browser console:
> undebug(myFunc)
If we do not want this breakpoint anymore, we can just refresh the page.
Another option is to use the function undebug()
.
"monitor" and "unmonitor"
Sometimes we do not want a breakpoint, we just want to know if a function is called.
In this cases we can use function monitor()
.
// Somewhere in the source code:
function myFunc() { ... }
// In the browser console:
> monitor(myFunc)
// A function of an object:
> monitor(myObject.myFunc)
// When "myFunc" is called the next time,
// an output will be written in the console.
// Remove the monitoring with browser console:
> unmonitor(myFunc)
As with the function debug
, a page reload can be used to stop the monitoring.
Another option is to use the function unmonitor()
.