MutationObserver – 如何在 Java 中使用

什么是突变观测器?

Mutation Observer 是一个内置对象,提供了一种观察 DOM 变化并对其做出反应的方法。它是构建需要实时 DOM 操作和事件处理的动态网络应用程序的强大工具。通过 Mutation Observer,您可以监控文档中特定节点、属性或子元素的变化,并执行自定义函数来响应这些变化。

在 Aspose.HTML for Java 库中, MutationObserver 类代表了一种文档观察机制,该类易于配置,可以接收文档树中任何变化的通知。本文使用 Java 示例来说明如何使用 MutationObserver 类来观察 DOM 中的变化。

如何使用突变观测器

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

  1. 使用 HTMLDocument() 构造函数创建 HTMLDocument 类的新实例。
  2. 使用 MutationObserver() 构造函数创建一个新的 MutationObserver 对象。该构造函数将 MutationCallback 对象作为参数,用作处理突变的回调函数。
  3. 使用 MutationObserverInit() 构造函数创建 MutationObserverInit 对象。您可以指定要检测的变化类型。例如,在示例中将 ChildListSubtreeCharacterData 属性设置为 true
  4. 调用 observe() 方法开始观察 DOM 变化。当 <body> 元素或其子节点发生符合配置选项的变化时,将调用回调函数来处理这些变化。
  5. 编辑 HTML 文档。例如,使用 createElement() 方法创建一个新的 <p> 元素,并使用 appendChild() 方法将其添加到文档的正文中;使用 createTextNode() 方法创建一个内容为 “Hello, World!“的文本节点,并使用 appendChild() 方法将其添加为<p>元素的子节点。
  6. 一旦 DOM 树发生变化,就会触发 MutationObserver 回调函数,并向控制台打印一条信息,说明哪个节点被添加到了文档中。
 1// Monitor DOM tree changes using MutationObserver API in Aspose.HTML for Java
 2
 3// Create an empty HTML document
 4HTMLDocument document = new HTMLDocument();
 5
 6// Create an instance of the MutationObserver class
 7MutationObserver observer = new MutationObserver(new MutationCallback() {
 8
 9    @Override
10    public void invoke(com.aspose.html.utils.collections.generic.IGenericList<MutationRecord> mutations, MutationObserver mutationObserver) {
11        for (int i = 0; i < mutations.size(); i++) {
12            MutationRecord record = mutations.get_Item(i);
13            for (Node node : record.getAddedNodes().toArray()) {
14                System.out.println("The '" + node + "' node was added to the document.");
15            }
16        }
17    }
18});
19
20// Configure options for the MutationObserver
21MutationObserverInit config = new MutationObserverInit();
22config.setChildList(true);
23config.setSubtree(true);
24config.setCharacterData(true);
25
26// Pass to observer the target node to observe with the specified configuration
27observer.observe(document.getBody(), 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
31Element p = document.createElement("p");
32document.getBody().appendChild(p);
33
34// Create a text and append it to the paragraph
35Text text = document.createTextNode("Hello, World!");
36p.appendChild(text);
37
38System.out.println("Waiting for mutation. Press any key to continue...");
39System.in.read();

建议

  1. 配置 MutationObserver 时,选择特定目标并关注特定元素或属性,以优化性能并减少不必要的处理。
  2. 使用高效回调 – 保持回调函数中的逻辑轻量级,以防止出现性能瓶颈,尤其是在高突变率情况下。
  3. 使用配置选项–使用 MutationObserverInit 对象对观测参数进行微调。只包含必要的属性(如 ChildListSubtreeCharacterData),以优化流程。

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

您可以从 GitHub 下载完整的示例和数据文件。

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.