Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect, change or remove existing mutation observer

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.

like image 576
user3491877 Avatar asked Oct 20 '22 11:10

user3491877


1 Answers

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 } );
}
like image 200
mutationComment Avatar answered Jan 02 '23 21:01

mutationComment