(
page: Page,
selector: string,
options?: { includeUA?: boolean }
)
| 227 | * Inspect an element via CDP, returning full CSS cascade data. |
| 228 | */ |
| 229 | export async function inspectElement( |
| 230 | page: Page, |
| 231 | selector: string, |
| 232 | options?: { includeUA?: boolean } |
| 233 | ): Promise<InspectorResult> { |
| 234 | const session = await getOrCreateSession(page); |
| 235 | |
| 236 | // Get document root |
| 237 | const { root } = await session.send('DOM.getDocument', { depth: 0 }); |
| 238 | |
| 239 | // Query for the element |
| 240 | let nodeId: number; |
| 241 | try { |
| 242 | const result = await session.send('DOM.querySelector', { |
| 243 | nodeId: root.nodeId, |
| 244 | selector, |
| 245 | }); |
| 246 | nodeId = result.nodeId; |
| 247 | if (!nodeId) throw new Error(`Element not found: ${selector}`); |
| 248 | } catch (err: any) { |
| 249 | throw new Error(`Element not found: ${selector} — ${err.message}`); |
| 250 | } |
| 251 | |
| 252 | // Get element attributes |
| 253 | const { node } = await session.send('DOM.describeNode', { nodeId, depth: 0 }); |
| 254 | const tagName = (node.localName || node.nodeName || '').toLowerCase(); |
| 255 | const attrPairs = node.attributes || []; |
| 256 | const attributes: Record<string, string> = {}; |
| 257 | for (let i = 0; i < attrPairs.length; i += 2) { |
| 258 | attributes[attrPairs[i]] = attrPairs[i + 1]; |
| 259 | } |
| 260 | const id = attributes.id || null; |
| 261 | const classes = attributes.class ? attributes.class.split(/\s+/).filter(Boolean) : []; |
| 262 | |
| 263 | // Get box model |
| 264 | let boxModel = { |
| 265 | content: { x: 0, y: 0, width: 0, height: 0 }, |
| 266 | padding: { top: 0, right: 0, bottom: 0, left: 0 }, |
| 267 | border: { top: 0, right: 0, bottom: 0, left: 0 }, |
| 268 | margin: { top: 0, right: 0, bottom: 0, left: 0 }, |
| 269 | }; |
| 270 | |
| 271 | try { |
| 272 | const boxData = await session.send('DOM.getBoxModel', { nodeId }); |
| 273 | const model = boxData.model; |
| 274 | |
| 275 | // Content quad: [x1,y1, x2,y2, x3,y3, x4,y4] |
| 276 | const content = model.content; |
| 277 | const padding = model.padding; |
| 278 | const border = model.border; |
| 279 | const margin = model.margin; |
| 280 | |
| 281 | const contentX = content[0]; |
| 282 | const contentY = content[1]; |
| 283 | const contentWidth = content[2] - content[0]; |
| 284 | const contentHeight = content[5] - content[1]; |
| 285 | |
| 286 | boxModel = { |
no test coverage detected