Main Website
Scraping
Web Scraping
Updated on
May 21, 2024

Viewport in Puppeteer: How to Manipulate Default Size

In Puppeteer, viewport manipulation is particularly significant for tasks such as web scraping, testing web applications across different devices, and generating screenshots or PDFs of web pages. By adjusting the viewport size, developers can ensure that the content is displayed as intended, regardless of the device or screen resolution. In this article, we’ll explore viewport manipulation in Puppeteer, beginning with an overview of its default size. We’ll cover methods to customize viewport dimensions and maximize it to match window size.

Puppeteer default viewport

The default viewport utilized by Puppeteer is 800 pixels wide, 600 pixels tall, with a device scale factor of 1

  • Width and Height: The dimensions of 800 pixels width and 600 heights are commonly used to simulate a typical desktop browser window. This size allows for rendering of most web pages without significant distortion or overflow.
  • Device Scale Factor: The device scale factor of 1 indicates a 1:1 mapping between CSS pixels and device pixels. This means that one CSS pixel corresponds to one device pixel, ensuring accurate representation of web content without any scaling applied.

Now let’s illustrate how to obtain the default viewport size using Puppeteer:


const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Get the default viewport size
  const defaultViewport = page.viewport();

  console.log('The default viewport size is:', defaultViewport);

  await browser.close();
})();

This code demonstrates how to launch a Puppeteer-controlled browser, create a new page, and retrieve the default viewport size using the page.viewport() method. Here’s the obtained viewport size:

Changing the viewport size

In Puppeteer, changing the viewport size is straightforward and can be accomplished using the setViewport method available on the Page object. This method allows developers to specify custom dimensions for the viewport, enabling them to simulate various screen sizes and orientations for testing and automation purposes.

The setViewport method

The setViewport method in Puppeteer allows developers to define the dimensions of the viewport using the following parameters:

  • width: Specifies the width of the viewport in pixels.
  • height: Specifies the height of the viewport in pixels.
  • deviceScaleFactor (optional): Defines the ratio of device pixels to CSS pixels. This parameter is useful for high-density displays where one CSS pixel may correspond to multiple device pixels.
  • isMobile (optional): Indicates whether the viewport should emulate a mobile device. When set to true, Puppeteer applies mobile-specific viewport settings, such as user agent and touch event emulation.

The following code demonstrates how to change the viewport size in Puppeteer and navigate to a web page using the custom viewport dimensions:


const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  // Set custom viewport size
  await page.setViewport({ 
    width: 1200, 
    height: 800,
    deviceScaleFactor: 1,
    isMobile: false 
  });

  // Navigate to a web page
  await page.goto('https://www.webshare.io/');

  await browser.close();
})();

By setting a custom viewport size using setViewport method, you can accurately simulate different browsing environments and ensure that web pages are rendered appropriately during automated interactions with Puppeteer.

Setting viewport to maximum (Window size)

In Puppeteer, setting the viewport size to match the window size involves retrieving the dimensions of the window and applying them to the viewport. This ensures that the viewport encompasses the entire visible area of the browser window.

To achieve this, you can use the page.setViewport method with the width and height parameters set to the dimensions of the window.


const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // Get window size
  const { width, height } = await page.evaluate(() => {
    return {
      width: window.innerWidth,
      height: window.innerHeight
    };
  });

  // Set viewport size to match window size
  await page.setViewport({ width, height });

  await browser.close();
})();

Why to set the viewport to the maximum window size

Setting the viewport size to match the window size offers several benefits:

  • Accurate Rendering: By aligning the viewport with the window size, developers ensure that web pages are rendered accurately, reflecting how they would appear to the user in a maximized browser window.
  • Responsive Design Testing: Mimicking the maximum window size allows for comprehensive testing for responsive designs, ensuring that web pages adapt seamlessly to different screen resolutions and orientations.
  • Consistent Automation: Setting the viewport to match the window size promotes consistency in automation tasks as it provides a standardized viewing area for interactions with web pages.

The captureBeyondViewport method

The captureBeyondViewport method in Puppeteer allows developers to capture content that extends beyond the viewport boundaries. This is useful for capturing entire web pages, including content that is only visible after scrolling.

This method enables the creation of full-page screenshots or PDFs, ensuring that no content is omitted during the capture process. By specifying the fullPage: true option when using page.screenshot or page.pdf, Puppeteer automatically captures content beyond the viewport, producing snapshots of web pages.


const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://books.toscrape.com/');

  // Capture screenshot including content beyond viewport
  await page.screenshot({ path: 'fullpage.png', fullPage: true, captureBeyondViewport: true });

  await browser.close();
})();

Here’s the output:

Troubleshooting common errors

Below we’ll address some common issues users may face when working with viewport manipulation in Puppeteer and provide possible solutions to overcome them effectively.

Puppeteer setViewport not working

Possible Causes

This issue may arise due to various reasons, such as incorrect usage of the setViewport method, timing issues, or conflicts with other page settings.

Solution

  • Ensure that the setViewport method is called after the page is created but before navigating to any URLs.
  • Double-check the parameters passed to the setViewport method to ensure they are valid.
  • Consider using page.waitForNavigation() to ensure that the page navigation is complete before setting the viewport.

Page content not fully visible within viewport

Possible Causes

The page content may not be fully visible within the viewport due to incorrect viewport dimensions or content overflow.

Solution

  • Ensure that the viewport dimensions are sufficient to display the entire page content without scrolling. Use larger dimensions if necessary.
  • Check for content overflow, such as elements extending beyond the viewport boundaries, and address them by adjusting CSS or layout properties
  • If specific elements are not visible within the viewport, use Puppeteer’s scrollIntoView method to scroll them into view before interacting with them.

Conclusion

In this article, we’ve explored viewport manipulation in Puppeteer, crucial for accurate rendering and responsive testing. We discussed changing viewport sizes, troubleshooting common issues like setViewport failures, and ensuring content visibility.

waitForNavigation in Puppeteer: Basic and Advanced Configuration

Get Element in Puppeteer: Mastering Class, ID and Text Methods

How to Get HTML in Puppeteer?