Conditional BreakPoint depending on another breakpoint in Chrome Dev Tools

497 Views Asked by At

I need to stop at breakpoint only if the code was stopped first in another breakpoint.
Example:

for(let i=0; i<5; i++){

   someFunction();           // put conditional breakpoint here with i==3
   
}

function someFunction(){

   // put another breakpoint here, but this should be executed only for i==3 
   // we don't have i here for the condition, so it should be executed only if prev breakpoint was executed

}

Is this possible with Chrome Dev Tools?

1

There are 1 best solutions below

0
On

You can actually write arbitrary code when you create a conditional breakpoint. You can write an entire block of code (use shift-enter to write multi-line code) if you want, using any JS you want. Any const/let/var declarations will only be accessible in the scope of this code block. Use global variables to pass data to other conditional breakpoints, or any code that you want to manually run in the DevTools console. If you don't want to actually stop on this breakpoint, just use false as the last expression of your code.

In your case, set the conditional breakpoint for the someFunction() line: _i = i, false or _i = i; false; (_i is the same as window._i in this case), just make sure to use a unique enough name to avoid conflicts with some other code from you or some 3rd party library that you use.

Inside the function, set a conditional breakpoint with _i == 3 as the condition.

As I found out, you can do all sorts ot neat tricks with conditional breakpoints:

  • Save a reference to some class instance in a global variable, then reference it on the console to check its properties or call its methods
  • Modify any variable in scope
  • Add some logging (DevTools also have a "logpoint" type of breakpoint for this, it's in a dropdown when you edit a breakpoint)

Another note: if you have any syntax errors in the code you use in a conditional breakpoint, the whole code block will not be executed, and the breakpoint won't be triggered. So if your conditional breakpoint code doesn't seem to be working, check it for errors - e.g. set a regular breakpoint there, trigger it, then execute the code you were trying to use in a conditional breakpoint in the console to see what's the problem with it.