-
-
Save pirate-barbosa/7d0f153fb28529e8e28494c27ceff640 to your computer and use it in GitHub Desktop.
Log all DOM mutations to console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Log all DOM mutations to console. | |
| // Modern interpretation of https://github.com/kdzwinel/DOMListenerExtension | |
| observer = new MutationObserver(onMutation); | |
| observerSettings = { | |
| subtree: true, | |
| childList: true, | |
| attributes: true, | |
| attributeOldValue: true, | |
| characterData: true, | |
| characterDataOldValue: true, | |
| }; | |
| function onMutation(records) { | |
| for (const record of records) { | |
| if (record.type === 'childList') { | |
| record.addedNodes.forEach(observeShadowRoots); | |
| } | |
| logMutation(record); | |
| } | |
| } | |
| function logMutation(r) { | |
| console.log(r.type, {el: r.target}, | |
| r.type === 'childList' | |
| ? Object.fromEntries(['addedNodes', 'removedNodes'].filter(key => r[key].length).map(key => ([key, r[key]]))) | |
| : r.type === 'attributes' | |
| ? [r.attributeName, r.oldValue, '➤', r.target.getAttribute(r.attributeName)] | |
| : undefined, | |
| {record: r}, | |
| ); | |
| } | |
| function observeShadowRoots(node) { | |
| findShadowRoots(node).forEach((shadowRoot) => { | |
| observer.observe(shadowRoot, observerSettings); | |
| }); | |
| } | |
| function findShadowRoots(node, list = new Set()) { | |
| if (node.shadowRoot) list.add(node.shadowRoot); | |
| node?.querySelectorAll && node.querySelectorAll('*').forEach((child) => { | |
| if (child.shadowRoot) findShadowRoots(child, list); | |
| }); | |
| return list; | |
| } | |
| // console.clear(); | |
| observer.disconnect(); // call manually to stop logging | |
| observer.observe(document, observerSettings); | |
| observeShadowRoots(document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment