How to set max viewport in Puppeteer?

前端 未结 8 921
一整个雨季
一整个雨季 2021-02-01 02:04

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

await page.setViewport({
    width: 1920,
    height: 108         


        
相关标签:
8条回答
  • 2021-02-01 02:39
    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.

    0 讨论(0)
  • 2021-02-01 02:41

    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.

    0 讨论(0)
提交回复
热议问题