MutationObserver – How to Use in C#

What Is Mutation Observer?

Mutation Observer is a built-in object that watches for DOM tree changes and calls or fires a callback function to react to the changes in the DOM. Watching changes in the DOM tree is periodically necessary for complex web applications and frameworks. With the Mutation Observer, you can monitor changes to a document’s specific nodes, attributes, or child elements and execute custom functions responding to those changes.

In the Aspose.HTML for .NET library, a document observation mechanism is represented with MutationObserver, which is highly configurable and allows you to be notified of any changes in the document tree. This article uses C# examples to show how you can use the MutationObserver class to observe changes in the DOM.

How To Use Mutation Observer

Mutation Observer provides the ability to observe changes in the DOM tree of a web page. 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. This class represents an HTML document in memory that can be parsed and modified.
  2. Create a new MutationObserver object using the MutationObserver(callback) constructor. The callback function takes mutations (a list of MutationRecord objects ) and mutationObserver (the MutationObserver object that detected the mutations) as parameters.
  3. Use the MutationObserverInit() constructor to create a MutationObserverInit object to configure the options for the MutationObserver. In other words, you can specify what kind of changes to detect. For example, ChildList, Subtree, and CharacterData properties are set to true in the example:
    • 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. Call the Observe(target, options) method to watch the DOM changes. This method takes the document.Body as the target node to observe and the config object as the options for the observation.
  5. Edit the HTML document:
  1. As soon as a DOM tree change occurs, such as adding the <p> element and the text node in this case, the MutationObserver callback function is fired, and it prints a message to the console indicating which node was added to the document.

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.

 1// For complete examples and data files, please go to https://github.com/aspose-html/Aspose.HTML-for-.NET
 2// Create an empty HTML document
 3using (var document = new HTMLDocument())
 4{
 5    // Create a mutation observer instance
 6    var observer = new Aspose.Html.Dom.Mutations.MutationObserver((mutations, mutationObserver) =>
 7    {
 8        foreach (var record in mutations)
 9        {
10            foreach (var node in record.AddedNodes)
11            {
12                Console.WriteLine("The '" + node + "' node was added to the document.");
13            }
14        }
15    });
16
17    // configuration of the observer
18    var config = new Aspose.Html.Dom.Mutations.MutationObserverInit
19    {
20        ChildList = true,
21        Subtree = true,
22        CharacterData = true
23    };
24
25    // pass in the target node to observe with the specified configuration
26    observer.Observe(document.Body, config);
27
28    // Now, we are going to modify DOM tree to check
29    // Create an paragraph element and append it to the document body
30    var p = document.CreateElement("p");
31    document.Body.AppendChild(p);
32    // Create a text and append it to the paragraph
33    var text = document.CreateTextNode("Hello World");
34    p.AppendChild(text);
35
36    Console.WriteLine("Waiting for mutation. Press any key to continue...");
37    Console.ReadLine();
38}

Aspose.HTML offers HTML Web Applications that are an online collection of free converters, mergers, SEO tools, HTML code generators, URL tools, and more. The applications work on any operating system with a web browser and do not require any additional software installation. Easily convert, merge, encode, generate HTML code, extract data from the web, or analyze web pages in terms of SEO wherever you are. Use our collection of HTML Web Applications to perform your daily matters and make your workflow seamless!

Text “Banner HTML Web Applications”

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.