How to set max viewport in Puppeteer?

前端 未结 8 1160
一整个雨季
一整个雨季 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: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.

提交回复
热议问题