简体   繁体   中英

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

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.

添加DOM断点

You can't.

MutationObserver returns the MutationRecord which only describes the changes themselves.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM