导航栏: 首页 评论列表

获取shadowDOM的innerHTML

默认分类 2019/04/29 11:07

问题描述: 无法直接获取到shadowDOM的innerHTML

解决思路:递归找出每个节点的shadowRoot的innerHTML和childNodes的innerHTML

代码如下:

function getDeepInnerHTML(nodelist, type) {
  var result = []
  for (let i = 0, len = nodelist.length; i < len; i++) {
    let item = nodelist[i]
    let str = ''
    if (item && item.id) console.log(item.id)
    if (item && item.id && item.id === 'content') {
      // debugger
    } 
    if (!item) continue
    if (item.nodeValue) {
      result.push(item.nodeValue)
      continue
    }
    let startTag = '', endTag = ''
    if (item.outerHTML) {
      let list = item.outerHTML.replace(item.innerHTML, '').split('</')
      if (list.length > 1) endTag = '</' + list.pop()
      startTag = list.join('</')
      result.push(startTag)
    }
    if (item.shadowRoot) {
      str = getDeepInnerHTML(item.shadowRoot.childNodes || [], 'string')
      result.push(str)
    }
    if (item.childNodes) {
      str = getDeepInnerHTML(item.childNodes, 'string')
      result.push(str)
    }
    if (item.outerHTML) {
      result.push(endTag)
    }
  }
  return type === 'string' ? result.join('') : result
}

console.log(getDeepInnerHTML(document.body.childNodes, 'string'))


>> 留言评论