'How to revert DOM changes from MutationObserver?
I am making a Chrome extension and have a content script that runs on a website. My script has a Mutation Observer on the document body, and I would like to prevent or revert changes from happening. I need to prevent/revert all of the mutations in the mutationsList after finding the correct mutationsList.
const targetElement = document.body;
const config = {
attributes: true,
childList: true,
subtree: true
};
const callback = (mutationsList, observer) => {
// Find the mutationsList that includes the #example-id mutations
const isExampleMutation = mutationsList.find(mutation => mutation.target.id === "example-id");
if (isExampleMutation) {
// How do I prevent/revert all of the mutations in mutationsList here?
}
}
// Create Mutation Observer
const observer = new MutationObserver(callback);
// Observe the target
observer.observe(targetElement, config);
Solution 1:[1]
This should be straightforward. You can't prevent the changes, but you could undo them immediately.
- Create a copy of the element you wish to "freeze." You could do this by storing the original, "correct"
innerHTML(orouterHTML), or via Element.cloneNode() - When your observer notices a change, simply overwrite the modified node with the original content. I think your overwrite will also trigger the mutation observer, creating an endless loop, so you'll need to set some kind of flag that tells the observer callback to ignore mutation events temporarily.
Note that every time you do this, you'll lose any event handlers that were bound to elements within the overwritten subtree. The only sane way I think you could avoid that would be to use delegated event handlers attached to elements outside the frozen tree, so they won't get blown away.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tom |
