Chrome DevTools has supported conditional breakpoints since, at least, July of 2015, but I'm embarrassed to admit that I've never tried them until now.
I found myself (as I often do...) trying to track down exactly why a service worker was behaving in a certain way when processing incoming requests in its
fetch handler(s). If this were code for my own project, I'd (no judgment!) throw in a ton of
console.log() statements and make sense of what got spit out on the Console after redeploying. But since I was looking at someone else's code, that debugging technique wasn't feasible. (Well, actually it is, but I needed something more powerful and less noisy than a bunch of logging.)
Instead, I remembered that conditional breakpoints could be set at runtime, and decided to give them try.
In this case, I wanted to start debugging at the very start of a
fetch event handler, but only if the handler were processing an incoming request for a specific type of URL. I was dealing with code generated by Workbox, and it was minimized, so finding the exact place to start debugging was a bit of a challenge.
Taking DevTools up on its offer to pretty-print the source code was the first step:
Next, I searched the source code for the string
fetch. Even though most of the symbols were minimized, string constants like
addEventListener('fetch', ...) were still intact, so finding that is reliable.
Once I found the right spot, I right-clicked on the line number where I wanted to conditionally enter the debugger:
There were a lot of different requests being made, but I knew that the one I cared about had a URL containing
common. I also knew that even through the variable was renamed to
e during minification, the parameter passed to a
fetch event listener is a
FetchEvent. That, in turn has a
request, and that has a
url property string. So
e.request.url would give me access to a URL that I could conditionally match:
If I were trying to debug something different, like tracing the logic used for all image requests, I could use different properties of the
Request, leading to a condition like
e.request.destination === 'image'.
In this particular case, there were actually two
fetch event handlers, which is a valid thing to have! This is an implementation detail that might change in the future, but Workbox currently creates one for its precache logic, and one for its runtime logic. So what I actually had to do was assign conditional breakpoints inside both of those handlers to figure out which one was running.