Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the function which caused a DOM mutation with a MutationObserver?

I am currently trying to figure out which function modified the DOM using a MutationObserver. The following snippet unfortunately doesn't work (the stack trace seems to be empty).

var targetNode = document.body;
var config = { attributes: true, childList: true, subtree: true };
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
      // The trace unfortunatelly doesn't contain the function 
      // "addSomeElement", which I am trying to receive at this point.
      console.trace(); 
    }
};

var observer = new MutationObserver(callback);
observer.observe(targetNode, config);

which is followed by some DOM mutation:

function addSomeElement() {
  targetNode.appendChild(document.createElement('span'));
}
addSomeElement();

Is there any way how I could output the function which does the actual mutation call (in this case the appendChild)?

like image 557
Julius Avatar asked Oct 12 '25 07:10

Julius


2 Answers

Use a DOM breakpoint (should work in Chrome and Firefox)

Developer Tools
-> Inspector
-> Right click on the element you want to monitor
-> Break on: Subtree modifications

When the child elements of the selected node are changed the browser will break on the responsible piece of JavaScript.

Adding DOM breakpoint

like image 125
Andreas Avatar answered Oct 13 '25 21:10

Andreas


You can't.

MutationObserver returns the MutationRecord which only describes the changes themselves.

It doesn't provide information about how those changes were effected.

like image 44
nicholaswmin Avatar answered Oct 13 '25 20:10

nicholaswmin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!