MutationObserver – 监控 HTML 文档中的 DOM 变化

什么是突变观测器?

突变观察器(Mutation Observer)是一个内置对象,用于观察 DOM 树的变化,并调用或触发回调函数来对 DOM 中的变化做出反应。对于复杂的网络应用程序和框架来说,定期观察 DOM 树的变化是必要的。利用突变观察器,您可以监控文档特定节点、属性或子元素的变化,并执行自定义函数来响应这些变化。

在 Aspose.HTML for .NET 库中, MutationObserver 代表了一种文档观察机制,该机制具有很高的可配置性,可以通知您文档树中的任何变化。本文使用 C# 示例来说明如何使用 MutationObserver 类来观察 DOM 中的变化。

如何使用突变观测器

Mutation Observer 提供了观察网页 DOM 树变化的功能。下面的示例演示了 MutationObserver 的实现,以及如何使用它来观察向文档中添加新节点的情况:

  1. 使用 HTMLDocument() 构造函数创建 HTMLDocument 类的新实例。该类在内存中表示一个可以解析和修改的 HTML 文档。
  2. 使用 MutationObserver(callback) 构造函数创建一个新的 MutationObserver 对象。callback 函数以 mutations(MutationRecord 对象列表)和 mutationObserver(检测到突变的 MutationObserver 对象)作为参数。
  3. 使用 MutationObserverInit() 构造函数创建一个 MutationObserverInit 对象来配置 MutationObserver 的选项。换句话说,您可以指定要检测的变化类型。例如,在示例中,ChildList、Subtree 和 CharacterData 属性被设置为 true:
    • ChildList detects changes in direct children of targetNode.
    • Subtree detects changes in all descendants of the node.
    • CharacterData is used to observe the changes in text content.
  4. 调用 Observe(target, options) 方法来观察 DOM 的变化。该方法将 document.Body 作为要观察的 target 节点,并将 config 对象作为观察的 options
  5. 编辑 HTML 文档
  1. 一旦 DOM 树发生变化,例如在本例中添加了 <p> 元素和文本节点,MutationObserver callback 函数就会被触发,并向控制台打印一条信息,说明文档中添加了哪个节点。

如果您正在观察节点的变化,那么在 DOM 完全完成变化之前,您的回调将不会被触发。设计这种行为是为了取代 DOM 突变事件,减少以前规范中的杀毒性能问题。

 1// Use Mutation Observer to watch for new nodes added to a document with C#
 2
 3// Create an empty HTML document
 4using (HTMLDocument document = new HTMLDocument())
 5{
 6    // Create a mutation observer instance
 7    Html.Dom.Mutations.MutationObserver observer = new Html.Dom.Mutations.MutationObserver((mutations, mutationObserver) =>
 8    {
 9        foreach (MutationRecord record in mutations)
10        {
11            foreach (Node node in record.AddedNodes)
12            {
13                Console.WriteLine("The '" + node + "' node was added to the document.");
14            }
15        }
16    });
17
18    // Configuration of the observer
19    MutationObserverInit config = new Html.Dom.Mutations.MutationObserverInit
20    {
21        ChildList = true,
22        Subtree = true,
23        CharacterData = true
24    };
25
26    // Pass in the target node to observe with the specified configuration
27    observer.Observe(document.Body, config);
28
29    // Now, we are going to modify DOM tree to check
30    // Create a paragraph element and append it to the document body
31    Element p = document.CreateElement("p");
32    document.Body.AppendChild(p);
33
34    // Create a text and append it to the paragraph
35    Text text = document.CreateTextNode("Hello, World");
36    p.AppendChild(text);
37
38    Console.WriteLine("Waiting for mutation. Press any key to continue...");
39    Output.ToString();
40}

Aspose.HTML 提供 HTML 网络应用程序,它是免费转换器、合并器、搜索引擎优化工具、HTML 代码生成器、URL 工具等的在线集合。这些应用程序可在任何装有网络浏览器的操作系统上运行,无需安装任何其他软件。无论你身在何处,都能轻松转换、合并、编码、生成 HTML 代码,从网络中提取数据,或从搜索引擎优化的角度分析网页。使用我们的 HTML 网络应用程序集来处理您的日常事务,让您的工作流程天衣无缝!

文本 “HTML 网络应用程序”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.