Detect, change or remove existing mutation observe

2019-06-28 08:50发布

问题:

If a mutation observer is added by some JS is it possible for other JS to detect, remove, replace or change that observer? My concern is that if some JS aims to corrupt some DOM element without being discovered that JS may want to get rid of any observers watching that DOM element.

回答1:

I'm not sure about detecting whether an observer is already installed, but they can be effectively deleted by re-observing the nodes of interest using an empty function. Re-observing a node will replace the previous observer function if one was present.

var observerRef = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

// Empty function here to replace whatever might have been installed on targets
var observer = new observerRef( function (mutations) { } );

// Could also be id=someid, etc
var targets = document.querySelectorAll('[class=someclassname]'); 

// Update/replace the observers on all the targets
for(var i = 0; i < targets.length; ++i) {
    observer.observe(targets[i], { attributes: true, childList: true, characterData: false } );
}