fix: support clip in ElementHandle.screenshot (#12115)

This commit is contained in:
Alex Rudenko 2024-03-21 09:16:24 +01:00 committed by GitHub
parent 93e9acc410
commit b096ffaa03
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 41 additions and 8 deletions

View File

@ -68,7 +68,7 @@ clip
</td><td>
Specifies the region of the page to clip.
Specifies the region of the page/element to clip.
</td><td>

View File

@ -1236,9 +1236,9 @@ export abstract class ElementHandle<
this: ElementHandle<Element>,
options: Readonly<ElementScreenshotOptions> = {}
): Promise<string | Buffer> {
const {scrollIntoView = true} = options;
const {scrollIntoView = true, clip} = options;
let clip = await this.#nonEmptyVisibleBoundingBox();
let elementClip = await this.#nonEmptyVisibleBoundingBox();
const page = this.frame.page();
@ -1247,7 +1247,7 @@ export abstract class ElementHandle<
await this.scrollIntoViewIfNeeded();
// We measure again just in case.
clip = await this.#nonEmptyVisibleBoundingBox();
elementClip = await this.#nonEmptyVisibleBoundingBox();
}
const [pageLeft, pageTop] = await this.evaluate(() => {
@ -1259,10 +1259,16 @@ export abstract class ElementHandle<
window.visualViewport.pageTop,
] as const;
});
clip.x += pageLeft;
clip.y += pageTop;
elementClip.x += pageLeft;
elementClip.y += pageTop;
if (clip) {
elementClip.x += clip.x;
elementClip.y += clip.y;
elementClip.height = clip.height;
elementClip.width = clip.width;
}
return await page.screenshot({...options, clip});
return await page.screenshot({...options, clip: elementClip});
}
async #nonEmptyVisibleBoundingBox() {

View File

@ -274,7 +274,7 @@ export interface ScreenshotOptions {
*/
path?: string;
/**
* Specifies the region of the page to clip.
* Specifies the region of the page/element to clip.
*/
clip?: ScreenshotClip;
/**

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 B

View File

@ -393,6 +393,33 @@ describe('Screenshots', function () {
await context.close();
});
it('should use element clip', async () => {
const {page} = await getTestState();
await page.setViewport({width: 500, height: 500});
await page.setContent(`
something above
<style>div {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div></div>
`);
using elementHandle = (await page.$('div'))!;
const screenshot = await elementHandle.screenshot({
clip: {
x: 10,
y: 10,
width: 20,
height: 20,
},
});
expect(screenshot).toBeGolden('screenshot-element-clip.png');
});
});
describe('Cdp', () => {