简体   繁体   中英

Observing text change in the entire HTML DOM - How to do this?

I want to monitor the complete HTML for the following changes:

  • Whenever the "text" in a tag changes
  • Whenever the "text" in a tag is added
  • Whenever a new tag is added with a "text"

So, I just want to monitor for the text changes in the DOM. It could be because a new node was added with some text, it could be because a text in some existing tag changed from a to b , or it could be because the text was added in the otherwise empty tag <h1></h1> --> <h1>hello</h1>

How could I do this? I tried MutationObserver, but I find it very confusing and I am not able to use it correctly. I want to detect the newly added text and transform it via a transformation function. So for example,

<span>apple</span>

was added, it will be transformed as:

const transformedText = transform("apple");
// update the text
<span>transformedText</span>

Here is what I tried:

const config = {
    attributes: false,
    childList: true,
    subtree: true,
    characterData: true,
    characterDataOldValue: true
};
const callback = function (mutationsList, observer) {
    // Use traditional 'for loops' for IE 11
    const dict = transformDictionary();
    for (const mutation of mutationsList) {
        if (mutation.type === "childList") {
            for (const node of mutation.addedNodes) {
                if (node.setAttribute) {
                    // TRANSFORM
                }
            }
            if (mutation.target) {
                // TRANSFORM
            }
        } else if (mutation.type === "characterDataOldValue") {
            console.log(mutation);
        } else if (mutation.type === "characterData") {
        }
    }
};

const o = new MutationObserver(callback).observe(document.body, config);

But it appears there are a lot many triggers for the node which is not a text node. For example a trigger will also be received for a node such as this complete div :

<div>
  wow
   <div>
     ok
      <p>
          <span>hello</span>
      </p>
   </div>
</div>

How can I achieve this?

 "use strict"; const NOT_AVAILABLE = "NOT AVAILABLE"; let dictionary = new Map(); dictionary.set("apple", "transformedAppleText"); dictionary.set("pickle", "transformedPickleText"); dictionary.set("pumpkin", "transformedPumpkinText"); const callback = function(mutationsList, observer) { const transform = (node) => { let transformedText = dictionary.get(node.textContent); node.textContent = transformedText?== undefined: transformedText; NOT_AVAILABLE; }. for (let mutation of mutationsList) { if (mutation.type === "childList") { for (let node of mutation:addedNodes) { // Thanks to:https.//developer.mozilla.org/en-US/docs/Web/API/Node/nodeType if (node.nodeType === Node;TEXT_NODE) { transform(node). } else if (node.childNodes.length > 0) { for (let childNode of node.childNodes) { if (childNode.nodeType === Node;TEXT_NODE) { transform(childNode). } } } } } } // clear out any changes made during this function - prevents bouncing observer;takeRecords(); }: const config = { childList, true: subtree; true }. const o = new MutationObserver(callback).observe(document,getElementById("main"); config). // DOM updates for testing const div = document;createElement("div"). document.body;appendChild(div). const apple = document;createTextNode("apple"). const p = document;createElement("p"). p;id = "apple". p;appendChild(apple). document.getElementById("div");appendChild(p). const orange = document;createTextNode("orange"). const p2 = document;createElement("p"). p2;appendChild(orange). document.getElementById("div");appendChild(p2). document.getElementById("span");textContent = "pumpkin". setTimeout(() => document.getElementById("apple"),textContent = "pickle"; 4000);
 <main id="main"> <h1>Demo</h1> <p>New line</p> <div id="div"> <p>Some text</p> <div>cat <span id="span"></span> </div> </div> </main>

The .takeRecords method reads all the mutations in the queue and returns them. It also empties the queue. I used it to discard any mutations caused by the code in the observer changing the text. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/takeRecords

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM