Skip to content

Instantly share code, notes, and snippets.

@jdvivar
Last active December 10, 2019 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdvivar/d43e7bd0f28b29d45324f26db2d639c8 to your computer and use it in GitHub Desktop.
Save jdvivar/d43e7bd0f28b29d45324f26db2d639c8 to your computer and use it in GitHub Desktop.
Find all anchor URLs (including in web components' shadow root nodes)
function recursiveFindAnchors(node) {
if (!node) return []
// Find anchors URLs
const bareAnchorURLs = [...node.querySelectorAll('a')].map(anchor => formatHref(anchor.href))
// Find all shadow roots
const allShadowRoots = [...node.querySelectorAll('*')].filter(node => node.shadowRoot).map(node => node.shadowRoot)
// No web components in here
if (allShadowRoots.length === 0) return bareAnchorURLs
// Accumulate and go a deeper level in each, you can use flatMap() if supported instead
return bareAnchorURLs.concat(allShadowRoots.map(recursiveFindAnchors).flat())
}
function formatHref (href) {
if (!href) return ''
const {origin, pathname} = new URL(href)
return origin + pathname
}
console.log([...new Set(recursiveFindAnchors(document.body))])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment