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:
- 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.
- Create a new MutationObserver object using the
MutationObserver(callback) constructor. The
callback
function takesmutations
(a list of MutationRecord objects ) andmutationObserver
(the MutationObserver object that detected the mutations) as parameters. - 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.
- Call the
Observe(target, options) method to watch the DOM changes. This method takes the
document.Body
as thetarget
node to observe and theconfig
object as theoptions
for the observation. - Edit the HTML document:
- use the CreateElement() method of the HTMLDocument class to create a new
<p>
element, and use the AppendChild() method to append it to the Body of the document. - use the CreateTextNode() method of the HTMLDocument class to create a text node with the content “Hello, World”, and use the AppendChild() method to append it as a child node to the
<p>
element.
- As soon as a DOM tree change occurs, such as adding the
<p>
element and the text node in this case, the MutationObservercallback
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// Create an empty HTML document
2using (var document = new HTMLDocument())
3{
4 // Create a mutation observer instance
5 var observer = new Html.Dom.Mutations.MutationObserver((mutations, mutationObserver) =>
6 {
7 foreach (var record in mutations)
8 {
9 foreach (var node in record.AddedNodes)
10 {
11 Console.WriteLine("The '" + node + "' node was added to the document.");
12 }
13 }
14 });
15
16 // Configuration of the observer
17 var config = new Html.Dom.Mutations.MutationObserverInit
18 {
19 ChildList = true,
20 Subtree = true,
21 CharacterData = true
22 };
23
24 // Pass in the target node to observe with the specified configuration
25 observer.Observe(document.Body, config);
26
27 // Now, we are going to modify DOM tree to check
28 // Create a paragraph element and append it to the document body
29 var p = document.CreateElement("p");
30 document.Body.AppendChild(p);
31
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 Output.ToString();
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!