feat: handle selector generation if no parent element

This commit is contained in:
amhsirak
2024-12-07 23:45:07 +05:30
parent 9f24e0018c
commit 8c4c0b734d

View File

@@ -753,7 +753,6 @@ interface SelectorResult {
export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates): Promise<SelectorResult> => { export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates): Promise<SelectorResult> => {
try { try {
const selectors = await page.evaluate(({ x, y }: { x: number, y: number }) => { const selectors = await page.evaluate(({ x, y }: { x: number, y: number }) => {
function getNonUniqueSelector(element: HTMLElement): string { function getNonUniqueSelector(element: HTMLElement): string {
let selector = element.tagName.toLowerCase(); let selector = element.tagName.toLowerCase();
@@ -775,18 +774,25 @@ export const getNonUniqueSelectors = async (page: Page, coordinates: Coordinates
let depth = 0; let depth = 0;
const maxDepth = 2; const maxDepth = 2;
while (element && element !== document.body && depth < maxDepth) { // Ensure we start with a valid element
const selector = getNonUniqueSelector(element); let currentElement = element;
while (currentElement && currentElement !== document.body && depth < maxDepth) {
const selector = getNonUniqueSelector(currentElement);
path.unshift(selector); path.unshift(selector);
element = element.parentElement; currentElement = currentElement.parentElement;
depth++; depth++;
} }
return path.join(' > '); return path.join(' > ');
} }
const element = document.elementFromPoint(x, y) as HTMLElement | null; // Find the initial element at the point
if (!element) return null; const initialElement = document.elementFromPoint(x, y) as HTMLElement;
if (!initialElement) return null;
// Prefer parent if exists, otherwise use initial element
const element = initialElement.parentElement || initialElement;
const generalSelector = getSelectorPath(element); const generalSelector = getSelectorPath(element);
return { return {