如何获取包含 shadowRoot 元素的文档或节点中的所有 HTML

How can I get all the HTML in a document or node containing shadowRoot elements

我还没有看到这个问题的满意答案。这基本上是 this question 的重复,但它被不正确地关闭并且给出的答案不充分。

我已经想出了我自己的解决方案,我将在下面post。

这对于网络抓取很有用,或者在我的例子中,运行 在处理自定义元素的 javascript 库上进行测试。我确保它正在生成我想要的输出,然后我使用此函数为给定的测试输出抓取 HTML,并将复制的 HTML 用作 预期 输出以在将来与测试进行比较。

这是一个可以执行请求的函数。请注意,它会忽略 html 评论和其他边缘内容。但它会使用 shadowRoots 检索常规元素、文本节点和自定义元素。它还处理开槽模板内容。它没有经过详尽的测试,但似乎可以很好地满足我的需要。

extractHTML(document.body)extractHTML(document.getElementByID('app'))一样使用它。

function extractHTML(node) {
            
    // return a blank string if not a valid node
    if (!node) return ''

    // if it is a text node just return the trimmed textContent
    if (node.nodeType===3) return node.textContent.trim()

    //beyond here, only deal with element nodes
    if (node.nodeType!==1) return ''

    let html = ''

    // clone the node for its outer html sans inner html
    let outer = node.cloneNode()

    // if the node has a shadowroot, jump into it
    node = node.shadowRoot || node
    
    if (node.children.length) {
        
        // we checked for children but now iterate over childNodes
        // which includes #text nodes (and even other things)
        for (let n of node.childNodes) {
            
            // if the node is a slot
            if (n.assignedNodes) {
                
                // an assigned slot
                if (n.assignedNodes()[0]){
                    // Can there be more than 1 assigned node??
                    html += extractHTML(n.assignedNodes()[0])

                // an unassigned slot
                } else { html += n.innerHTML }                    

            // node is not a slot, recurse
            } else { html += extractHTML(n) }
        }

    // node has no children
    } else { html = node.innerHTML }

    // insert all the (children's) innerHTML 
    // into the (cloned) parent element
    // and return the whole package
    outer.innerHTML = html
    return outer.outerHTML
    
}

只有使用 mode:"open" 设置创建 shadowRoots 才能从外部访问 shadowRoots。

然后您可以潜入 元素和 shadowRoots 与 something 比如:

 const shadowDive = (
          el, 
          selector, 
          match = (m, r) => console.warn('match', m, r)
  ) => {
    let root = el.shadowRoot || el;
    root.querySelector(selector) && match(root.querySelector(selector), root);
    [...root.children].map(el => shadowDive(el, selector, match));
  }

注意:如果 Web 组件样式基于 shadowDOM 行为,提取原始 HTML 是没有意义的;您将失去所有正确的样式。