MutationObserver – How to Use in Java

What Is Mutation Observer?

Mutation Observer is a built-in object that provides a way to observe and react to changes in the DOM. It is a powerful tool for building dynamic web applications that require real-time DOM manipulation and event handling. With the Mutation Observer, you can monitor changes to specific nodes, attributes, or child elements of a document and execute custom functions that respond to those changes.

In Aspose.HTML for Java library, a document observation mechanism is represented with MutationObserver,which is easy to configure and makes it possible to receive notifications of any changes in the document tree. This article uses Java examples to show how you can use the MutationObserver class to observe changes in the DOM.

How To Use Mutation Observer

A document observation mechanism is represented with MutationObserver, that is easy to configure, and it is used to register listeners that can be notified of any changes in the document tree. The following example demonstrates the implementation of MutationObserver and how to use it to observe adding new nodes to the document.

  1. Create a new instance of the HTMLDocument class using HTMLDocument() constructor.
  2. Create a new MutationObserver object using the MutationObserver() constructor. The constructor takes a MutationCallback object as a parameter, which is used as a callback function for handling mutations.
  3. Use the MutationObserverInit() constructor to create a MutationObserverInit object. You can specify what kind of changes to detect. For example, ChildList, Subtree, and CharacterData properties are set to true in the example.
  4. Call the observe() method to start observing the DOM changes. When changes occur in the <body> element or its child nodes that match the configured options, the callback function will be invoked to handle those mutations.
  5. Edit the HTML document. For example, use the createElement() method to create a new <p> element, and use the appendChild() method to append it to the body of the document; use the createTextNode() method to create a text node with the content “Hello World”, and use the appendChild() method to add it as a child node to the <p> element.
  6. As soon as a DOM tree change occurs, the MutationObserver callback function is fired, and it prints a message to the console indicating which node was added to the document.
 1// Create an empty HTML document
 2com.aspose.html.HTMLDocument document = new com.aspose.html.HTMLDocument();
 3
 4// Create an instance of the MutationObserver
 5com.aspose.html.dom.mutations.MutationObserver observer = new com.aspose.html.dom.mutations.MutationObserver(new com.aspose.html.dom.mutations.MutationCallback() {
 6     @Override
 7    public void invoke(com.aspose.html.utils.collections.generic.IGenericList<com.aspose.html.dom.mutations.MutationRecord> mutations, com.aspose.html.dom.mutations.MutationObserver mutationObserver) {
 8        for (int i = 0 ; i < mutations.size(); i++) {
 9            com.aspose.html.dom.mutations.MutationRecord record = mutations.get_Item(i);
10            for (com.aspose.html.dom.Node node : record.getAddedNodes().toArray()) {
11                System.out.println("The '" + node + "' node was added to the document.");
12            }
13        }
14    }
15});
16
17// Configure options for the MutationObserver
18com.aspose.html.dom.mutations.MutationObserverInit config = new com.aspose.html.dom.mutations.MutationObserverInit();
19config.setChildList(true);
20config.setSubtree(true);
21config.setCharacterData(true);
22
23// Pass to observer the target node to observe with the specified configuration
24observer.observe(document.getBody(), config);
25
26// Now, we are going to modify DOM tree to check
27// Create a paragraph element and append it to the document body
28com.aspose.html.dom.Element p = document.createElement("p");
29document.getBody().appendChild(p);
30
31// Create a text and append it to the paragraph
32com.aspose.html.dom.Text text = document.createTextNode("Hello World");
33p.appendChild(text);
34
35System.out.println("Waiting for mutation. Press any key to continue...");
36System.in.read();

If you are observing a node for changes, your callback will not be fired until the DOM has completely finished changing. This behavior was designed to replace DOM Mutation Events and reduce the killing performance issue in the previous specification.

You can download the complete examples and data files from GitHub.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.