From 240d51f1d38ce9f203f1cba2aca40cbdb7dcfd2d Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Thu, 19 Nov 2020 13:55:14 -0800 Subject: [PATCH] docs: improve boundingBox documentation (#4500) Also add a test to verify it. --- docs/api.md | 13 ++++++++++++- test/elementhandle-bounding-box.spec.ts | 19 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs/api.md b/docs/api.md index fd969b62d1..80329d2ad1 100644 --- a/docs/api.md +++ b/docs/api.md @@ -3012,7 +3012,18 @@ expect(await feedHandle.$$eval('.tweet', nodes => nodes.map(n => n.innerText))). - width <[number]> the width of the element in pixels. - height <[number]> the height of the element in pixels. -This method returns the bounding box of the element (relative to the main frame), or `null` if the element is not visible. +This method returns the bounding box of the element, or `null` if the element is not visible. The bounding box is calculated relative to the main frame viewport - which is usually the same as the browser window. + +Scrolling affects the returned bonding box, similarly to [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). That means `x` and/or `y` may be negative. + +Elements from child frames return the bounding box relative to the main frame, unlike the [Element.getBoundingClientRect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect). + +Assuming the page is static, it is safe to use bounding box coordinates to perform input. For example, the following snippet should click the center of the element. + +```js +const box = await elementHandle.boundingBox(); +await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2); +``` #### elementHandle.check([options]) - `options` <[Object]> diff --git a/test/elementhandle-bounding-box.spec.ts b/test/elementhandle-bounding-box.spec.ts index 1c954959b6..14568ecca9 100644 --- a/test/elementhandle-bounding-box.spec.ts +++ b/test/elementhandle-bounding-box.spec.ts @@ -37,6 +37,25 @@ it('should handle nested frames', async ({ page, server }) => { expect(box).toEqual({ x: 24, y: 224, width: 268, height: 18 }); }); +it('should handle scroll offset and click', async ({ page, server }) => { + await page.setContent(` + +
+
+
+
+ `); + const elementHandle = await page.$('#target'); + const box1 = await elementHandle.boundingBox(); + await page.evaluate(() => window.scrollBy(200, 300)); + const box2 = await elementHandle.boundingBox(); + expect(box1).toEqual({ x: 230, y: 340, width: 20, height: 20 }); + expect(box2).toEqual({ x: 30, y: 40, width: 20, height: 20 }); + await page.mouse.click(box2.x + 10, box2.y + 10); + expect(await page.evaluate(() => window['__clicked'])).toBe(true); +}); + it('should return null for invisible elements', async ({ page, server }) => { await page.setContent('
hi
'); const element = await page.$('div');