New 'watch-element' debugging snippet
Why?
Anytime we suspect that an ad is being added to the page on client-side via an inline script or something similar, we want to see the content that was added. One approach is to use DOM modifications breakpoints in the Debugging Tools of a browser, but this is not always reliable (sometimes gets ignored after page refresh), nor enough configurable. We basically want to mimic the behaviour of a DOM breakpoint but using a snippet. And, apart from that, we will log/highlight the modified elements.
What?
A snippet that watches for a DOM element mutations. It logs and highlights the element that was added and/or sets a breakpoint each time that happens.
How?
There are 2 major implementation steps:
- Watching the document to react when the target element is being added to the DOM
- using MutationObserver
- Finding the parent element and configure it's DOM mutation properties with a getter/setter in order to be able to add logging and highlighting
- In case we want the behaviour to be attached to the entire subtree, the snippet:
- recursively configures all the children's DOM mutation properties
- attaches a MutationObserver to this parent element in order to configure all the new added children's DOM mutation properties
DOM mutation properties
- appendChild
- append
- insertBefore
- replaceChild
- insertAdjacentElement
- insertAdjacentHTML
- innerHTML
- textContent
Parameters
Name | Description | Example | Mandatory |
---|---|---|---|
selector | The CSS selector for the parent element that we want to watch | '.left-content .container' |
yes |
options | A single parameter for snippet's options. A string containing all the options we want to pass, each of them separated by a plus character (+ ). Empty single quotes if none ('' ). Available options: subtree (watch the entire subtree of the element), breakpoint (add a debugger breakpoint each time on each addition) |
subtree or subtree+breakpoint or ''
|
no |
Examples
Filter | Result |
---|---|
watch-element ol#b_results subtree+breakpoint |
Logs, highlights and adds a debugger breakpoint anytime a new child is added to the entire subtree of the ol#b_results element. |
watch-element ol#b_results subtree |
Logs and highlights the elements added to the entire subtree of the ol#b_results element. |
watch-element ol#b_results breakpoint |
Logs, highlights and adds a debugger breakpoint anytime a new direct/first-level child is added to the ol#b_results element. |
watch-element ol#b_results |
Logs and highlights the elements added as direct/first-level children to the ol#b_results element. |
Options syntax
In order to support multiple optional parameters, I proposed a syntax for the options parameter. For example, let's say in the future the snippet will need to support a new optional parameter. In this case, the second parameter needs to be skipped (see ''
proposal). What do you think about it?