Julius
Julius

Reputation: 1265

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)?

Upvotes: 4

Views: 1406

Answers (2)

Andreas
Andreas

Reputation: 21881

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

Upvotes: 9

nicholaswmin
nicholaswmin

Reputation: 22939

You can't.

MutationObserver returns the MutationRecord which only describes the changes themselves.

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

Upvotes: 2

Related Questions