How do I use Playwright to emulate different devices?

Playwright provides powerful device emulation capabilities that allow you to test how your web applications behave on different devices. This is essential for responsive design testing and mobile web development.

Installation

Python

pip install playwright
playwright install

JavaScript/TypeScript

npm install playwright
npx playwright install

Using Predefined Device Descriptors

Playwright includes over 100 predefined device descriptors that simulate real devices with accurate viewport sizes, user agents, and device capabilities.

Python Example

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    # Choose a device descriptor
    device = p.devices["iPhone 13"]

    browser = p.webkit.launch()
    context = browser.new_context(
        **device,
        locale="en-US",
        geolocation={"longitude": -122.4194, "latitude": 37.7749},
        permissions=["geolocation"]
    )

    page = context.new_page()
    page.goto("https://example.com")
    page.screenshot(path="mobile-view.png")
    browser.close()

JavaScript Example

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

(async () => {
  const iPhone13 = devices['iPhone 13'];

  const browser = await webkit.launch();
  const context = await browser.newContext({
    ...iPhone13,
    locale: 'en-US',
    geolocation: { longitude: -122.4194, latitude: 37.7749 },
    permissions: ['geolocation'],
  });

  const page = await context.newPage();
  await page.goto('https://example.com');
  await page.screenshot({ path: 'mobile-view.png' });
  await browser.close();
})();

Popular Device Descriptors

Here are some commonly used device descriptors:

Mobile Devices

  • "iPhone 13", "iPhone 12", "iPhone SE"
  • "Pixel 5", "Galaxy S21", "Galaxy Note 20"

Tablets

  • "iPad Pro", "iPad Mini"
  • "Galaxy Tab S7"

Desktop

  • "Desktop Chrome HiDPI", "Desktop Firefox HiDPI"

Custom Device Configuration

You can create custom device emulation by specifying viewport size, user agent, and other properties:

Python Example

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    context = browser.new_context(
        viewport={"width": 390, "height": 844},
        user_agent="Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15",
        device_scale_factor=3,
        is_mobile=True,
        has_touch=True
    )

    page = context.new_page()
    page.goto("https://example.com")
    browser.close()

JavaScript Example

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

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext({
    viewport: { width: 390, height: 844 },
    userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15',
    deviceScaleFactor: 3,
    isMobile: true,
    hasTouch: true,
  });

  const page = await context.newPage();
  await page.goto('https://example.com');
  await browser.close();
})();

Testing Multiple Devices

You can test multiple devices in a single script:

Python Example

from playwright.sync_api import sync_playwright

devices_to_test = ["iPhone 13", "iPad Pro", "Pixel 5"]

with sync_playwright() as p:
    browser = p.webkit.launch()

    for device_name in devices_to_test:
        device = p.devices[device_name]
        context = browser.new_context(**device)
        page = context.new_page()

        page.goto("https://example.com")
        page.screenshot(path=f"{device_name.replace(' ', '_')}-screenshot.png")

        context.close()

    browser.close()

JavaScript Example

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

const devicesToTest = ['iPhone 13', 'iPad Pro', 'Pixel 5'];

(async () => {
  const browser = await webkit.launch();

  for (const deviceName of devicesToTest) {
    const device = devices[deviceName];
    const context = await browser.newContext(device);
    const page = await context.newPage();

    await page.goto('https://example.com');
    await page.screenshot({ path: `${deviceName.replace(/\s+/g, '_')}-screenshot.png` });

    await context.close();
  }

  await browser.close();
})();

Advanced Device Features

Network Conditions

# Python - Simulate slow network
context = browser.new_context(
    **p.devices["iPhone 13"],
    # Simulate slow 3G network
    offline=False,
    # Additional network throttling would require CDP
)

Geolocation and Permissions

// JavaScript - Device with location permissions
const context = await browser.newContext({
  ...devices['iPhone 13'],
  geolocation: { longitude: -74.006, latitude: 40.7128 }, // New York
  permissions: ['geolocation', 'camera', 'microphone'],
});

Key Device Properties

When using device descriptors, Playwright automatically sets: - Viewport size: Screen dimensions - User agent: Browser identification string
- Device scale factor: Pixel density - Mobile flag: Whether device is mobile - Touch support: Touch event capabilities

Best Practices

  1. Choose appropriate browsers: Use WebKit for iOS devices, Chromium for Android
  2. Test responsive breakpoints: Test key viewport sizes for your design
  3. Consider network conditions: Emulate slower connections for mobile testing
  4. Verify touch interactions: Ensure touch events work correctly on mobile
  5. Test orientation changes: Some devices support landscape/portrait modes

Viewing Available Devices

To see all available device descriptors:

# Python
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    devices = list(p.devices.keys())
    print(f"Available devices ({len(devices)}):")
    for device in sorted(devices):
        print(f"  - {device}")
// JavaScript
const { devices } = require('playwright');

const deviceNames = Object.keys(devices);
console.log(`Available devices (${deviceNames.length}):`);
deviceNames.sort().forEach(name => console.log(`  - ${name}`));

Device emulation in Playwright is a powerful feature that enables comprehensive cross-device testing without requiring physical devices.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon