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 } );
}