Skip to content

Commit

Permalink
Fix to get correct inline element position (Xetera#15)
Browse files Browse the repository at this point in the history
* Fix to get correct inline element position

Some elements like <a> split in multiple lines at small screens.

* Based on Niek suggestion removed page.evaluate
  • Loading branch information
kbourro authored Nov 24, 2020
1 parent e1bb034 commit ad91cf4
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion src/spoof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,41 @@ export const getRandomPagePoint = async (page: Page): Promise<Vector> => {
return getRandomBoxPoint({ x: origin.x, y: origin.y, width: window.bounds.width, height: window.bounds.height })
}

// Using this method to get correct position of Inline elements (elements like <a>)
const getElementBox = async (page: Page, element: ElementHandle, relativeToMainFrame: boolean = true): Promise<Box | null> => {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
if ((element as any)._remoteObject === undefined || (element as any)._remoteObject.objectId === undefined) {
return null
}
const quads = await (page as any)._client.send('DOM.getContentQuads', {
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
objectId: (element as any)._remoteObject.objectId
})
const elementBox = {
x: quads.quads[0][0],
y: quads.quads[0][1],
width: quads.quads[0][4] - quads.quads[0][0],
height: quads.quads[0][5] - quads.quads[0][1]
}
if (elementBox === null) {
return null
}
if (!relativeToMainFrame) {
const elementFrame = (element.executionContext() as any).frame()
const iframes = await elementFrame.parentFrame().$x('//iframe')
let frame = null
for (const iframe of iframes) {
if ((await iframe.contentFrame()) === elementFrame) frame = iframe
}
if (frame !== null) {
const boundingBox = await (frame as ElementHandle).boundingBox()
elementBox.x = boundingBox !== null ? elementBox.x - boundingBox.x : elementBox.x
elementBox.y = boundingBox !== null ? elementBox.y - boundingBox.y : elementBox.y
}
}
return elementBox
}

const isBox = (a: any): a is Box => 'width' in a

export function path (point: Vector, target: Vector, spreadOverride?: number)
Expand Down Expand Up @@ -194,7 +229,7 @@ export const createCursor = (page: Page, start: Vector = origin, performRandomMo
objectId: (elem as any)._remoteObject.objectId
})
}
const box = await elem.boundingBox()
const box = await getElementBox(page, elem)
if (box === null) {
throw new Error("Could not find the dimensions of the element you're clicking on, this might be a bug?")
}
Expand Down

0 comments on commit ad91cf4

Please sign in to comment.