How can I simulate a specific screen resolution using Puppeteer?
Alex K
alex k profile pic

To simulate a specific screen resolution using Puppeteer, you can utilize thepage.setViewport() method to set the viewport dimensions of the page. 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. Simulating a specific screen resolution usingpage.setViewport(): To simulate a specific screen resolution, you can use thepage.setViewport() method to set the desired width and height for the viewport.

1
2
3
4
5
6
7
8
9

   const desiredWidth = 1280;
   const desiredHeight = 800;

   await page.setViewport({ width: desiredWidth, height: desiredHeight });

   // Proceed with further actions on the page
   await page.goto('https://example.com');
   

In this example,page.setViewport() is called with an object containing thewidth andheight properties set to the desired values. This method sets the dimensions of the viewport to simulate the specified screen resolution. After setting the viewport, you can proceed with further actions on the page, such as navigating to a specific URL. By utilizing thepage.setViewport() method, you can simulate a specific screen resolution in Puppeteer. This is useful for testing responsive designs, capturing screenshots or videos at different resolutions, or replicating the user experience on different devices during web automation tasks.