Skip to content

Instantly share code, notes, and snippets.

@jonathantneal
Last active January 17, 2025 14:18
Show Gist options
  • Save jonathantneal/1b25514f6120254b152d1232896a9f1e to your computer and use it in GitHub Desktop.
Save jonathantneal/1b25514f6120254b152d1232896a9f1e to your computer and use it in GitHub Desktop.
Logic used to get a NodeID from an element using CDP
const getNodeId = async (element: Element) => {
const selectors = getUniqueSelectors(element)
const root = (await cdp().send("DOM.getDocument", { depth: -1 })).root
let nodeId = root.nodeId
for (const selector of selectors) {
if (nodeId !== root.nodeId) {
const next = await cdp().send("DOM.describeNode", { nodeId })
if (next.node.contentDocument?.nodeId) {
nodeId = next.node.contentDocument.nodeId
}
}
nodeId = (
await cdp().send("DOM.querySelector", {
nodeId,
selector,
})
).nodeId
}
return nodeId
}
const getUniqueSelectors = (element: Element): string[] => {
const selector = getUniqueSelector(element)
const root = element.getRootNode() as Document
return root instanceof Document && root.defaultView?.frameElement
? [...getUniqueSelectors(root.defaultView.frameElement), selector]
: [selector]
}
const getUniqueSelector = (element: Element) => {
/** Unique selector for this element */
let selector = ""
let parent: Element
let nth: number
while ((parent = element.parentElement!)) {
for (nth = 1; (element = element.previousElementSibling!); ++nth);
selector = " > :nth-child(" + nth + ")" + selector
element = parent
}
return ":root" + selector
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment