How to set max viewport in Puppeteer?
Asked Answered
O

9

67

When I run a new page, I must specify size of the viewport using the setViewport function:

await page.setViewport({
    width: 1920,
    height: 1080
})

I want use max viewport.

How can I make the viewport resizable according to the window size?

Occasional answered 28/9, 2018 at 10:23 Comment(0)
M
117

I may be very late on this. Nevertheless for others, try:

const browser = await puppeteer.launch({defaultViewport: null});

Set the defaultViewport option to null as above to disable the 800x600 resolution. It takes the max resolution then.

Meadowlark answered 22/3, 2019 at 14:59 Comment(4)
@gdoron It is mentioned in their documentation, puppeteer.launch(options) . See defaultViewport option, it clearly states that setting this to null, it disables the default viewport + it worked for me.Meadowlark
Worked for me with: const browser = await puppeteer.launch({ headless: false, defaultViewport: null });Wiggle
When disabling headless mode and visually launching Chromium, this confirms that the viewport uses its maximum allowed size. Together with pdf option preferCSSPageSize: true this allows for much easier styling of a pdf.Komsomolsk
In my case both your answer and the one of @Grant Miller (namely using the args to set the window size) have been the solutionSnitch
L
63

You can pass the --window-size flag as an argument to puppeteer.launch() to change the window size to your desired width and height.

Then you can call the Chrome Devtools Protocol method Emulation.clearDeviceMetricsOverride to clear the overridden device metrics (including the default 800 x 600 viewport).

This will cause the viewport to match the window size (when taking screenshots, etc).

const browser = await puppeteer.launch({
  args: [
    '--window-size=1920,1080',
  ],
});

const page = await browser.newPage();

await page._client.send('Emulation.clearDeviceMetricsOverride');

await page.screenshot({
  path: 'example.png', // Image Dimensions : 1920 x 1080
});

Note: page.viewport() will still return { width: 800, height: 600 }, and the only way to reliably change the values of these properties is to use page.setViewport().

See the complete example below:

'use strict';

const puppeteer = require('puppeteer');

(async () => {
  /* ============================================================
      Prerequisite: Set Window size
  ============================================================ */

  const browser = await puppeteer.launch({
    args : [
      '--window-size=1920,1080',
    ],
  });

  const page = await browser.newPage();

  await page.goto('https://www.example.com/');

  /* ============================================================
      Case 1: Default Viewport
  ============================================================ */

  console.log('Case 1 - Width  :', page.viewport().width);  // Width  : 800
  console.log('Case 1 - Height :', page.viewport().height); // Height : 600

  await page.screenshot({
    path: 'image-1.png', // Image Dimensions : 800 x 600
  });

  /* ============================================================
      Case 2: Clear Overridden Device Metrics
  ============================================================ */

  await page._client.send('Emulation.clearDeviceMetricsOverride');

  console.log('Case 2 - Width  :', page.viewport().width);  // Width  : 800
  console.log('Case 2 - Height :', page.viewport().height); // Height : 600

  await page.screenshot({
    path: 'image-2.png', // Image Dimensions : 1920 x 1080
  });

  /* ============================================================
      Case 3: Manually Set Viewport
  ============================================================ */

  await page.setViewport({
    width: 1920,
    height: 1080,
  });

  console.log('Case 3 - Width  :', page.viewport().width);  // Width  : 1920
  console.log('Case 3 - Height :', page.viewport().height); // Height : 1080

  await page.screenshot({
    path: 'image-3.png', // Image Dimensions : 1920 x 1080
  });

  /* ============================================================
      Case 4: Revert Back to Default Viewport
  ============================================================ */

  await page.setViewport({
      width: 800,
      height: 600,
  });

  console.log('Case 4 - Width  :', page.viewport().width);  // Width  : 800
  console.log('Case 4 - Height :', page.viewport().height); // Height : 600

  await page.screenshot({
    path: 'image-4.png', // Image Dimensions : 800 x 600
  });

  await browser.close();
})();
Lavinia answered 28/9, 2018 at 19:3 Comment(1)
tks, using await page._client.send('Emulation.clearDeviceMetricsOverride'); makes --window-size workFoxtrot
S
21

As explained in this issue

page.setViewport({ width: 0, height: 0 });

makes chromium set the viewport by inferring the current screen resolution. Seems to only work with headless: false

Sigmon answered 21/11, 2018 at 17:34 Comment(0)
V
17
const browser = await puppeteer.launch( {"headless": false, args: ['--start-maximized'] } );
const page = await browser.newPage();
await page.setViewport({width:0, height:0});

the " const browser = ..." line maximizes your chrome window. But note that the page is where the viewport needs to be set and it would still be at the default size when you create the page.

When you set the viewport with width and height as "0", the page viewport size becomes equal to size of the browser.

Valdavaldas answered 8/5, 2019 at 17:43 Comment(0)
M
14

It's probably worth mentioning that if you combine puppeteer.launch({defaultViewport: null}) with puppeteer.connect(), again you need to pass {defaultViewport: null}}, otherwise the viewport is adjusted back to default size. So in this case, use:

await puppeteer.connect({browserWSEndpoint: ws, defaultViewport: null})
Marlinemarlinespike answered 31/7, 2019 at 15:9 Comment(0)
W
14

I had the same problem and what worked for me is this.

const browser = await puppeteer.launch({
  headless: false,
  args: ['--window-size=1920,1080'],
  defaultViewport: null
  });
Wilful answered 21/8, 2020 at 10:59 Comment(1)
use await page._client.send('Emulation.clearDeviceMetricsOverride'); for when headless=trueFoxtrot
E
13

For me the combination of defaultViewport: null and args: ['--start-maximized'] gave me fullscreen with view fitting to screensize so:

browser = await puppeteer.launch({
            headless: false,
            args: [
                '--start-maximized',
            ],
            defaultViewport: null,
        }); 
Embolism answered 4/3, 2020 at 18:8 Comment(0)
E
3

Here is a way to do it at runtime by calling Page.setViewport() in headful and Browser.setWindowBounds() in headless via a Chrome Devtools Protocol session:

async function setWindowSize(page, width, height) {
  if(headless) {
    const session = await page.target().createCDPSession();
    const {windowId} = await session.send('Browser.getWindowForTarget');
    await session.send('Browser.setWindowBounds', {windowId, bounds: {width: width, height: height}});
    await session.detach();
  } else {
    await page.setViewport({width: width, height: height});
  }
}

See my comment on GitHub for more info.

Electrosurgery answered 17/11, 2020 at 3:12 Comment(0)
R
1

Here is another hack you can use:

    const yourDesiredHeight = await page.evaluate(() => {
      const elementHeight = document.querySelector(yourHTMLElement)
      return elementHeight && elementHeight.scrollHeight
    })
    await page.setViewport({
      width: parseInt(`${width}`) || 900,
      height: yourDesiredHeight || 600),
      deviceScaleFactor: parseInt(`${scale}`) == 2 ? 2 : 1
    })

Note: using document.body.scrollHeight may not give you what you want. You will need to use the scrollHeight of the specific element under consideration (which may be body).

Risinger answered 4/4, 2022 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.