Detect, change or remove existing mutation observe

2019-06-28 08:29发布

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条回答
Emotional °昔
2楼-- · 2019-06-28 09:23

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 } );
}
查看更多
登录 后发表回答