How to work with dynamically loaded shadow dom with mutation observer?

162 Views Asked by At

I have a webpage that dynamically loads a shadow dom. I have added mutation observer to the document that can not capture insertion of shadow dom. But I have to detect it onload.

I can observe the shadow dom by overloading the HtmlElement.prototype.attachShadow. But I need to observe it after loading.The shadow dom can be added to any other element. In this instance, the shadow dom is added to <div id="shadowHost">.

<!DOCTYPE html>
<html>
<head>
  <title>Load Iframe on Button Click</title>
</head>
<body>
  <button onclick="createIframe('./embedded_form.html')">Load Iframe</button>
  <button id="createShadowDomButton">Create Shadow DOM</button>
    <div id="shadowHost"><p>hello</p></div>
  <script>
    var attachShadow = HTMLElement.prototype.attachShadow;
    HTMLElement.prototype.attachShadow = function ( option )
    {
      var sh = attachShadow.call( this, option )
      console.info( '%s shadow attached to %s', option.mode, this )
      //add a MutationObserver here
      observer.observe(sh,{ childList: true });
      return sh;
    }
  </script>
  <script>
    const target = document.querySelector("body");
    function logNewNodes(records) {
      for (const record of records) {
            // Check if the childlist of the target node has been mutated
            if (record.type === "childList") {
              console.log(record.type);
            }
            console.log(record);
      }   
    }
    const observer = new MutationObserver(logNewNodes);
    observer.observe(target, { childList: true });
  </script>
  <script>
    // Function to create a Shadow DOM
function createShadowDOM() {
    const shadowHost = document.getElementById("shadowHost");

    // Check if Shadow DOM is supported by the browser
    if (shadowHost.attachShadow) {
        const shadowRoot = shadowHost.attachShadow({ mode: "open" });

        // Create a div inside the Shadow DOM
        const shadowDiv = document.createElement("div");
        shadowDiv.textContent = "This is a Shadow DOM element!";
        
        // Apply styles to the shadowDiv (optional)
        const style = document.createElement("style");
        style.textContent = `
            div {
                background-color: lightgray;
                padding: 10px;
                border: 1px solid gray;
            }
        `;
        shadowRoot.appendChild(style);

        // Append the shadowDiv to the Shadow DOM
        shadowRoot.appendChild(shadowDiv);
    } else {
        console.error("Shadow DOM is not supported in this browser.");
    }
}

// Add a click event listener to the button
const createShadowDomButton = document.getElementById("createShadowDomButton");
createShadowDomButton.addEventListener("click", createShadowDOM);

  </script>
</body>
</html>
0

There are 0 best solutions below