简体   繁体   English

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

[英]How to serialize an HTML DOM including Shadow DOM?

I want to serialize an entire HTML DOM including Shadow DOM trees into a string ie including both the shadow host and shadow root in a way that they can be reconstructed. 我想将整个HTML DOM(包括Shadow DOM树)序列化为一个字符串,即包含阴影主机和阴影根,以便可以重建它们。

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. 我可以通过.shadowRoot.innerHTML以编程方式访问Shadow DOM,但是在整个DOM上调用.outerHTML或使用XMLSerializer不包括shadowRoot。

Is there a way to serialize the entire HTML document including Shadow DOM trees? 有没有办法序列化整个HTML文档,包括Shadow DOM树?

I want to serialize an entire HTML DOM including Shadow DOM trees into a string ie including both the shadow host and shadow root in a way that they can be reconstructed. 我想将整个HTML DOM(包括Shadow DOM树)序列化为一个字符串,即包含阴影主机和阴影根,以便可以重建它们。

Note, shadowRoot nodes are not clonable; 注意, shadowRoot节点不可克隆; though you should be able to iterate childNodes of shadowRoot to retrieve .nodeValue or .innerHTML of each node within shadowRoot . 虽然你应该能够重复childNodesshadowRoot检索.nodeValue.innerHTML内的每个节点的shadowRoot

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

Alternatively you can call .innerHTML chained to .treeRoot property of shadowRoot to retrieve full html of shadowRoot . 另外,您可以拨打.innerHTML链接到.treeRoot财产shadowRoot检索全htmlshadowRoot

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. 我可以通过.shadowRoot.innerHTML以编程方式访问Shadow DOM,但是在整个DOM上调用.outerHTML或使用XMLSerializer不包括shadowRoot。

You can use .outerHTML called on .host to retrieve html of element within document which hosts shadowRoot . 您可以使用.outerHTML调用.host来检索托管shadowRoot document中的元素的html

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

The shadowRoot can then be reconstructed by creating a <template> element, setting .innerHTML to variable shadowHTML which is string .treeRoot.innerHTML ; 然后可以通过创建<template>元素重建shadowRoot ,将.innerHTML设置为变量shadowHTML ,即字符串.treeRoot.innerHTML ; appending newly created template element to a shadowRoot . 将新创建的template元素附加到shadowRoot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM