D3F4ULT
D3F4ULT

Reputation: 934

Is possible to detect a change in the DOM and make it not happen?

Is it possible to somehow monitor the DOM insertions and modifications to the DOM and then decide in some way it is done or not? Through some parameter to cancel the event or cause the event does not occur while I perform a custom action, eg one second callback.

No need to work in all browsers, more specifically I need it to apply in some situations and specifically'm performing tests on an extension that I'm creating for Google Chrome so the browser is Google Chrome.

There is an element in the DOM, which I modify it by extending and occurs right but this DOM element is updated after a certain action (send message) to send the DOM element is "upgraded" and returns to its original state removing the changes I made, what I need is to always keep my changes and not the "original" that is imposed by modifying the DOM through the site.

Upvotes: 3

Views: 2362

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276296

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.

Upvotes: 6

Related Questions