What is the Puppeteer API method to set the viewport size?
Rashid D
rashid d profile pic

The Puppeteer API method to set the viewport size ispage.setViewport(). Here's a detailed explanation: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

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

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Setting the viewport size usingpage.setViewport(): To set the viewport size of the page, you can use thepage.setViewport() method and pass an object specifying the desired width, height, and optional device scale factor.

1
2
3

   await page.setViewport({ width: 1280, height: 720 });
   

In this example,page.setViewport() is called to set the viewport size to a width of 1280 pixels and a height of 720 pixels. The default device scale factor is 1, which means 1 CSS pixel corresponds to 1 physical pixel on the device screen. You can adjust the width and height values to match your specific requirements. 3. Emulating mobile devices with preset viewports: Puppeteer also provides preset options to emulate various mobile devices. Instead of manually setting the viewport size, you can usepage.emulate() to emulate a specific device.

1
2
3

   await page.emulate(puppeteer.devices['iPhone X']);
   

In this code snippet,page.emulate() is called to emulate the viewport of an iPhone X. Puppeteer provides a list of pre-defined devices in thepuppeteer.devices object, allowing you to easily emulate popular devices without manually specifying the viewport size. By following these steps, you can set the viewport size using Puppeteer. Whether you need to specify a custom width and height or emulate a specific device, thepage.setViewport() method orpage.emulate() method (with pre-defined devices) allow you to control the viewport size and test your web application's responsiveness on different screen sizes and devices.