"is possible to detect a change in the dom and make it not happen?" Code Answer

4

watching for changes:

what you are looking for is a mutationobserver.

example from mdn

// select the target node
var target = document.queryselector('#some-id');

// create an observer instance
var observer = new mutationobserver(function(mutations) {
  mutations.foreach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childlist: true, characterdata: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

they work on recent versionf of chrome so you shouldn't have any problem using them in an extension.

as for rolling it back, i suspect you'd have to roll it back yourself.

here is a strategy for rolling back:

  1. clone the node you're watching using node.clonenode(true) (the parameter indicates a deep clone)
  2. watch the node with a mutation observer.
  3. call node.replacechild on it from its parent when it changes.

while this is not the most efficient approach it is the simplest and is simple enough to implement. a more drastic but perhaps faster approach would be reverting every mutation yourself using the returned mutation array.

preventing updates:

if you just want to prevent other code from touching it, there is a simpler way.

  1. clone the node using node.clonenode(true) (the parameter indicates a deep clone).
  2. wait until you're sure the external code calling it has obtained its reference to it.
  3. call node.replacechild on it from its parent, the external code now is holding a reference to a node that is not in the document and changes will not reflect in the presentation.
  4. additionally, you might want to change its id, class name, and other 'identifying' information so the external code won't catch it if it selects it lazily from the dom.
By KomalG on April 15 2022

Answers related to “is possible to detect a change in the dom and make it not happen?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.