Home  Puppeteer   How to emul ...

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:

  1. Launch Puppeteer with Mobile Emulation Options: Use Puppeteer's viewport and userAgent options 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();
    })();
    
  2. Selecting a Device: Puppeteer provides predefined devices that you can use for emulation. For example, 'iPhone X', 'iPad', 'Nexus 7', etc. These are defined in puppeteer.devices.

  3. 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, and deviceScaleFactor properties in setViewport based on the device you want to emulate.

  4. Testing Responsive Design: Mobile emulation is useful for testing responsive web design and ensuring that your website looks and functions correctly across different devices.

  5. Headless Mode: To run Puppeteer in headless mode (without a visible browser UI), simply remove the { headless: false } option from puppeteer.launch().

Published on: Jun 28, 2024, 12:41 AM  
 

Comments

Add your comment