How to emulate mobile devices in puppeteer
To emulate mobile devices using Puppeteer, you can configure the viewport and user agent of the browser page to simulate various mobile devices. Here’s a step-by-step guide on how to achieve this:
-
Launch Puppeteer with Mobile Emulation Options: Use Puppeteer's
viewportanduserAgentoptions to simulate a mobile device. Here's an example:const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ headless: false }); // Launch browser in non-headless mode for visibility const page = await browser.newPage(); // Emulate iPhone X const device = puppeteer.devices['iPhone X']; await page.emulate(device); // Navigate to a website await page.goto('https://example.com'); // Continue with your automation... await browser.close(); })(); -
Selecting a Device: Puppeteer provides predefined devices that you can use for emulation. For example,
'iPhone X','iPad','Nexus 7', etc. These are defined inpuppeteer.devices. -
Custom Device Configuration: If you need to emulate a specific device that isn't predefined, you can define custom viewport and user agent settings:
await page.setViewport({ width: 375, height: 667, isMobile: true, hasTouch: true, deviceScaleFactor: 2 }); await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14E5239e Safari/602.1');Adjust the
width,height,isMobile,hasTouch, anddeviceScaleFactorproperties insetViewportbased on the device you want to emulate. -
Testing Responsive Design: Mobile emulation is useful for testing responsive web design and ensuring that your website looks and functions correctly across different devices.
-
Headless Mode: To run Puppeteer in headless mode (without a visible browser UI), simply remove the
{ headless: false }option frompuppeteer.launch().