Search code examples
javascriptshadow-dommutation-observers

Setting a MutationObserver on a shadow root element


I'm currently trying to observe an element inside a shadow root that is populated when an error has occurred within the application. I'm targetting an element that's body is empty on page loads

<div id="errorContainer"></div>

however when an error occurs, is populated with div's. The structure of which looks like the following:

Image of DevTools DOM

Currently, when the page loads I have a function that is called checkforShadow() which gets the shadow root parent, gets the id of the element inside the shadow root I want to observe and initialises the observer.

const searchModule = document.querySelector('.campaign-map');
const searchModuleRoot = searchModule && searchModule.shadowRoot;

var errorContainer = searchModuleRoot.querySelector('#errorContainer');

// Create an observer instance.
var observer = new MutationObserver(function(mutations) {
    console.log(errorContainer.innerText);   
});

// Pass in the target node, as well as the observer options.
observer.observe(errorContainer , {
    attributes:    true,    // Monitor attribute changes
    childList:     true,    // Monitor child nodes of errorContainer
    subtree:       true,    // Monitor errorContainer and it's decendants for new/ removed child nodes
    characterData: true     // Monitor errorContainer (and it's children) for character changes
});

My understanding is that seeing as I have the childList and the subtree set as true, when errorContainer is populated, I should be able to see it log to the console.

I've also tried added a debugger into the observer instance however it never seems to get into it.

Am I missing something here?


Solution

  • As per @wOxxOm and @t-j-crowder said.

    Although I was observing the errorContainer, when an error occurred, it was replacing the container instead of adding elements to it.

    After adding the observer to an element inside the shadow root which was not replaced, I was able to transcend the DOM and determine whether or not the error container was being populated or not.