Detect, change or remove existing mutation observer

不问归期 提交于 2019-12-23 10:17:55

问题


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


来源:https://stackoverflow.com/questions/22826657/detect-change-or-remove-existing-mutation-observer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!