Last active
January 17, 2025 14:18
-
-
Save jonathantneal/1b25514f6120254b152d1232896a9f1e to your computer and use it in GitHub Desktop.
Logic used to get a NodeID from an element using CDP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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