Skip to content

Commit 76e1066

Browse files
authored
fix(screenshot): use innerW/H instead of offsetW/H to determine viewport size (#2229)
When capturing a screenshot with null viewport, we determine the screenshot size based on body.offsetHeight. This is a very large number for long pages. We should use window.innerHeight instead.
1 parent dbef7de commit 76e1066

File tree

2 files changed

+8
-11
lines changed

2 files changed

+8
-11
lines changed

src/screenshotter.ts

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,7 @@ export class Screenshotter {
4343
let viewportSize = originalViewportSize;
4444
if (!viewportSize) {
4545
const context = await this._page.mainFrame()._utilityContext();
46-
viewportSize = await context.evaluateInternal(() => {
47-
if (!document.body || !document.documentElement)
48-
return null;
49-
return {
50-
width: Math.max(document.body.offsetWidth, document.documentElement.offsetWidth),
51-
height: Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
52-
};
53-
});
54-
if (!viewportSize)
55-
throw new Error(kScreenshotDuringNavigationError);
46+
viewportSize = await context.evaluateInternal(() => ({ width: window.innerWidth, height: window.innerHeight }));
5647
}
5748
return { viewportSize, originalViewportSize };
5849
}

test/screenshot.spec.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
*/
1717

1818
const {FFOX, CHROMIUM, WEBKIT} = require('./utils').testOptions(browserType);
19+
const {PNG} = require('pngjs');
1920

2021
// Firefox headful produces a different image.
2122
const ffheadful = FFOX && !HEADLESS;
@@ -410,10 +411,15 @@ describe.skip(ffheadful)('ElementHandle.screenshot', function() {
410411
it('should take screenshots when default viewport is null', async({server, browser}) => {
411412
const context = await browser.newContext({ viewport: null });
412413
const page = await context.newPage();
413-
await page.goto(server.PREFIX + '/grid.html');
414+
await page.setContent(`<div style='height: 10000px; background: red'></div>`);
415+
const windowSize = await page.evaluate(() => ({ width: window.innerWidth * window.devicePixelRatio, height: window.innerHeight * window.devicePixelRatio }));
414416
const sizeBefore = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
417+
415418
const screenshot = await page.screenshot();
416419
expect(screenshot).toBeInstanceOf(Buffer);
420+
const decoded = PNG.sync.read(screenshot);
421+
expect(decoded.width).toBe(windowSize.width);
422+
expect(decoded.height).toBe(windowSize.height);
417423

418424
const sizeAfter = await page.evaluate(() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight }));
419425
expect(sizeBefore.width).toBe(sizeAfter.width);

0 commit comments

Comments
 (0)