javascript – 如何序列化包含Shadow DOM的HTML DOM?

我想将整个
HTML DOM(包括Shadow DOM树)序列化为一个字符串,即包括影子主机和影子根,以便可以重建它们.

我可以通过.shadowRoot.innerHTML以编程方式访问Shadow DOM,但是在整个DOM上调用.outerHTML或使用XMLSerializer不包括shadowRoot.

有没有办法序列化整个HTML文档,包括Shadow DOM树?

最佳答案

I want to serialize an entire HTML DOM including Shadow DOM trees into
a string i.e. including both the shadow host and shadow root in a way
that they can be reconstructed.

注意,shadowRoot节点不可克隆;虽然您应该能够迭代shadowRoot的childNodes来检索shadowRoot中每个节点的.nodeValue或.innerHTML.

var elems = document.getElementById("host").shadowRoot.childNodes;
var shadowHTML = "";
for (var i = 0; i < elems.length; i++) {
  shadowHTML += elems[i].nodeValue || elems[i].outerHTML;
}

或者,您可以将.innerHTML链接到shadowRoot的.treeRoot属性,以检索shadowRoot的完整html.

var shadowHTML = document.getElementById("host").shadowRoot.treeRoot.innerHTML;

I can programatically access the Shadow DOM via .shadowRoot.innerHTML
but calling .outerHTML on the entire DOM or using an XMLSerializer
does not include the shadowRoot.

您可以使用.hostHTML调用.host来检索托管shadowRoot的文档中的元素的html.

var host = document.getElementById("host").shadowRoot.host.outerHTML;

然后可以通过创建< template>来重建shadowRoot.元素,将.innerHTML设置为变量shadowHTML,它是字符串.treeRoot.innerHTML;将新创建的模板元素附加到shadowRoot.

点赞