JS - 監聽整個頁面上的 DOM 樹變化


在線預覽

使用《Web API 接口》的《MutationObserver》
MutationObserver

網上查到的很多都是使用 Mutation events 的,但在 MDN 上一查這個事件已經廢棄了,並且推薦用 MutationObserver 替換掉

Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Avoid using it and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

Mutation events provide a mechanism for a web page or an extension to get notified about changes made to the DOM. Use Mutation Observers instead if possible.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <h1>下述方法也可以監聽使用《谷歌頁面翻譯》時的DOM變化</h1>
    <h1>
      The following way also can catch changes of DOM when using
      <em>Google page translation</em>
    </h1>
    <h3>使用MutationObserver(Using MutationObserver)</h3>
    <div id="hello"><span>Hello</span> <em>Mr.</em> Word!</div>
    <button onclick="addNode()">添加(add DOM)</button>
    <script>
      // Select the node that will be observed for mutations
      var targetNode = document.querySelector("body");

      // Options for the observer (which mutations to observe)
      // subtree:是否監聽子節點的變化
      var config = { attributes: true, childList: true, subtree: true };

      // Callback function to execute when mutations are observed
      var callback = function(mutationsList) {
        for (var mutation of mutationsList) {
          console.log(mutation);
          if (mutation.type == "childList") {
            console.log("A child node has been added or removed.");
          } else if (mutation.type == "attributes") {
            console.log(
              "The " + mutation.attributeName + " attribute was modified."
            );
          }
        }
      };

      // Create an observer instance linked to the callback function
      var observer = new MutationObserver(callback);

      // Start observing the target node for configured mutations
      observer.observe(targetNode, config);

      // // Later, you can stop observing
      // observer.disconnect();

      var addNode = function() {
        var divnode = document.createElement("div");
        var textNode = document.createTextNode("Hello world!");
        divnode.appendChild(textNode);
        document.getElementById("hello").appendChild(divnode);
      };
    </script>
  </body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM