Home  Playwright   Mobile emul ...

Mobile emulation in Playwright

To simulate mobile emulation in Playwright, you need to set up a browser context with mobile device parameters such as viewport size, user agent, and device scale factor. Playwright provides built-in device descriptors for popular mobile devices, which makes it easier to emulate them.

Here's a step-by-step guide on how to do this:

Example

Here's a script to emulate a mobile device using Playwright:

const { chromium, devices } = require('playwright');

(async () => {
  // Select a device descriptor
  const iPhone11 = devices['iPhone 11'];

  // Launch the browser
  const browser = await chromium.launch();

  // Create a new browser context with mobile emulation
  const context = await browser.newContext({
    ...iPhone11,
    viewport: iPhone11.viewport,
    userAgent: iPhone11.userAgent
  });

  // Create a new page
  const page = await context.newPage();

  // Navigate to a webpage
  await page.goto('https://example.com');

  // Perform actions or assertions on the mobile emulated page
  console.log('Page title:', await page.title());

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

Explanation

  1. Select a Device Descriptor:

    const { chromium, devices } = require('playwright');
    const iPhone11 = devices['iPhone 11'];
    
    • devices provides built-in descriptors for various devices. In this example, we use the iPhone 11 descriptor.
  2. Launch the Browser:

    const browser = await chromium.launch();
    
  3. Create a New Browser Context with Mobile Emulation:

    const context = await browser.newContext({
      ...iPhone11,
      viewport: iPhone11.viewport,
      userAgent: iPhone11.userAgent
    });
    
    • browser.newContext() creates a new context with the device parameters from the iPhone 11 descriptor.
    • ...iPhone11 spreads the device properties into the context options.
  4. Create a New Page:

    const page = await context.newPage();
    
  5. Navigate to a Webpage:

    await page.goto('https://example.com');
    
  6. Perform Actions or Assertions on the Mobile Emulated Page:

    console.log('Page title:', await page.title());
    
  7. Close the Browser:

    await browser.close();
    

Running the Script

Save the script to a file (e.g., mobile_emulation.js) and execute it using Node.js:

node mobile_emulation.js

Available Device Descriptors

Playwright comes with a set of built-in device descriptors for popular devices. You can list all available devices using the following code:

const { devices } = require('playwright');

console.log(devices);

This will print a list of available device descriptors, which you can use to emulate different devices.

Published on: Jun 28, 2024, 03:25 AM  
 

Comments

Add your comment