提问人:noob kid 提问时间:9/27/2023 更新时间:9/27/2023 访问量:52
如何使用带有突变观察器的动态加载的阴影 dom?
How to work with dynamically loaded shadow dom with mutation observer?
问:
我有一个动态加载影子 dom 的网页。我已将突变观察器添加到无法捕获阴影 dom 插入的文档中。但我必须检测它。
我可以通过重载 HtmlElement.prototype.attachShadow 来观察阴影 dom。但是我需要在加载后观察它。shadow dom 可以添加到任何其他元素中。在本例中,将 shadow dom 添加到 中。<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>
答: 暂无答案
评论