VIEWPORT & DEVICE EMULATION

Master responsive design testing and mobile browser simulation in Playwright with Python: device descriptors registry, screen resolutions, touch gestures, device scale factors, orientation changes, and media query overrides.

📱 Responsive Testing & Device Emulation Architecture

Modern web applications must perform consistently across diverse hardware: desktop monitors, foldable tablets, and mobile smartphones. Playwright enables end-to-end device emulation through native browser capabilities rather than simple iframe resizing. By configuring viewports, user agents, device scale factors (Retina displays), touch screen interfaces, and screen orientations, test suites can validate responsive navigation bars, hamburger menus, and touch events without requiring expensive physical device farms.

1. Playwright Device Descriptors Registry (playwright.devices)
Playwright maintains a built-in dictionary of over 100 mobile, tablet, and desktop device profiles (e.g., iPhone 14 Pro Max, Pixel 7, iPad Mini), providing authentic user agents, viewports, pixel ratios, and touch flags.
Python (Inspecting Device Registry)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    # Query exact parameters of pre-configured device profiles
    pixel_7 = p.devices["Pixel 7"]
    iphone_14 = p.devices["iPhone 14 Pro"]

    print("=== Pixel 7 Emulation Profile ===")
    print(f"  User Agent       : {pixel_7['user_agent'][:50]}...")
    print(f"  Viewport Geometry: {pixel_7['viewport']['width']}x{pixel_7['viewport']['height']}")
    print(f"  Scale Factor     : {pixel_7['device_scale_factor']}x")
    print(f"  Touch Enabled    : {pixel_7['has_touch']}")
    print(f"  Mobile Mode      : {pixel_7['is_mobile']}")

    print("\n=== iPhone 14 Pro Emulation Profile ===")
    print(f"  Viewport Geometry: {iphone_14['viewport']['width']}x{iphone_14['viewport']['height']}")
    print(f"  Scale Factor     : {iphone_14['device_scale_factor']}x")
Output: === Pixel 7 Emulation Profile === User Agent : Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWeb... Viewport Geometry: 412x915 Scale Factor : 2.625x Touch Enabled : True Mobile Mode : True === iPhone 14 Pro Emulation Profile === Viewport Geometry: 393x852 Scale Factor : 3x
Real-Time Example 1: Emulating Mobile Smartphones (Pixel 7 / iPhone)
Unpack device profile dictionaries directly into browser.new_context(**profile) to launch an authentic mobile browser session and test responsive viewports.
Python (Mobile Context Initialization)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    # Load mobile profile and spawn context
    mobile_profile = p.devices["Pixel 7"]
    context = browser.new_context(**mobile_profile)
    page = context.new_page()

    page.goto("https://demo.playwright.dev/todomvc/")

    # Evaluate client-side properties inside the browser runtime
    device_metrics = page.evaluate("""() => ({
        innerWidth: window.innerWidth,
        innerHeight: window.innerHeight,
        pixelRatio: window.devicePixelRatio,
        isTouch: 'ontouchstart' in window,
        userAgent: navigator.userAgent
    })""")

    print("Client DOM Evaluation Results:")
    print(f"  Rendered Viewport : {device_metrics['innerWidth']}x{device_metrics['innerHeight']} px")
    print(f"  Device Pixel Ratio: {device_metrics['pixelRatio']}")
    print(f"  Touch Event API   : {'Supported' if device_metrics['isTouch'] else 'Disabled'}")

    context.close()
    browser.close()
Output: Client DOM Evaluation Results: Rendered Viewport : 412x915 px Device Pixel Ratio: 2.625 Touch Event API : Supported
Real-Time Example 2: Dynamic Viewport Resizing (Desktop, Tablet, Mobile)
Test fluid CSS media query breakpoints dynamically on an open page using page.set_viewport_size() without having to restart the browser context.
Python (Dynamic Breakpoint Testing)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto("https://example.com")

    # Responsive testing breakpoints
    test_breakpoints = [
        ("Desktop 1080p", 1920, 1080),
        ("Laptop Widescreen", 1366, 768),
        ("Tablet Portrait", 768, 1024),
        ("Mobile View", 375, 667)
    ]

    for label, width, height in test_breakpoints:
        page.set_viewport_size({"width": width, "height": height})
        actual_size = page.viewport_size
        print(f"Breakpoint [{label:18s}] -> Applied: {actual_size['width']}x{actual_size['height']} px")

    browser.close()
Output: Breakpoint [Desktop 1080p ] -> Applied: 1920x1080 px Breakpoint [Laptop Widescreen ] -> Applied: 1366x768 px Breakpoint [Tablet Portrait ] -> Applied: 768x1024 px Breakpoint [Mobile View ] -> Applied: 375x667 px
Real-Time Example 3: Simulating Touch Events & Mobile Gestures
When has_touch=True is configured, Playwright dispatches real TouchEvents (touchstart, touchmove, touchend) and supports mobile screen tap interactions via page.tap().
Python (Touch Events & Tap Interaction)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    
    # Configure custom context with touch dispatch enabled
    context = browser.new_context(
        viewport={"width": 390, "height": 844},
        has_touch=True,
        is_mobile=True
    )
    page = context.new_page()

    # Load interactive demo application
    page.goto("https://demo.playwright.dev/todomvc/")
    
    todo_input = page.get_by_placeholder("What needs to be done?")
    todo_input.fill("Touch Gesture Verification")
    todo_input.press("Enter")

    # Tap on the toggle button using touch interface
    toggle_checkbox = page.locator(".toggle")
    toggle_checkbox.tap()

    is_completed = page.locator(".todo-list li").first.get_attribute("class")
    print("Mobile Tap Event Dispatched Successfully.")
    print(f"Todo Item State: '{is_completed}'")

    context.close()
    browser.close()
Output: Mobile Tap Event Dispatched Successfully. Todo Item State: 'completed'
Real-Time Example 4: Screen Orientation Toggling (Portrait vs. Landscape)
Verify responsive design transitions when users rotate their mobile devices by swapping viewport width and height to simulate landscape and portrait orientations.
Python (Orientation Swapping)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    
    # Base iPad device profile
    ipad_profile = p.devices["iPad Pro 11"]
    context = browser.new_context(**ipad_profile)
    page = context.new_page()
    page.goto("https://example.com")

    # 1. Default Portrait Mode
    portrait_size = page.viewport_size
    print(f"iPad Portrait Viewport : {portrait_size['width']}x{portrait_size['height']} px")

    # 2. Simulate Device Rotation to Landscape Mode (Swap Width and Height)
    landscape_size = {"width": portrait_size["height"], "height": portrait_size["width"]}
    page.set_viewport_size(landscape_size)
    print(f"iPad Landscape Viewport: {page.viewport_size['width']}x{page.viewport_size['height']} px")

    # Assert layout accommodates wider landscape layout
    rendered_width = page.evaluate("window.innerWidth")
    print(f"Verified Active Window Width: {rendered_width} px")

    context.close()
    browser.close()
Output: iPad Portrait Viewport : 834x1194 px iPad Landscape Viewport: 1194x834 px Verified Active Window Width: 1194 px
Real-Time Example 5: High-DPI Retina Displays (device_scale_factor)
Standard desktop displays run at 1x scale, whereas modern smartphones and Apple Retina displays run at 2x or 3x. Setting device_scale_factor captures high-resolution screenshots and tests responsive srcset images.
Python (device_scale_factor Configuration)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    # 1. Standard Desktop 1x Density Context
    std_context = browser.new_context(viewport={"width": 800, "height": 600}, device_scale_factor=1)
    std_page = std_context.new_page()
    std_page.goto("https://example.com")
    std_dpr = std_page.evaluate("window.devicePixelRatio")

    # 2. Apple Retina 2x Density Context
    retina_context = browser.new_context(viewport={"width": 800, "height": 600}, device_scale_factor=2)
    retina_page = retina_context.new_page()
    retina_page.goto("https://example.com")
    retina_dpr = retina_page.evaluate("window.devicePixelRatio")

    print(f"Standard Display window.devicePixelRatio: {std_dpr}")
    print(f"Retina 2x Display window.devicePixelRatio: {retina_dpr}")
    print("Retina screenshots will render at double pixel resolution (1600x1200 image buffer).")

    std_context.close()
    retina_context.close()
    browser.close()
Output: Standard Display window.devicePixelRatio: 1 Retina 2x Display window.devicePixelRatio: 2 Retina screenshots will render at double pixel resolution (1600x1200 image buffer).
Real-Time Example 6: CSS Media Query Overrides (Dark Mode & Print)
Override browser display rendering using page.emulate_media() to test print preview stylesheets (@media print) and color schemes (prefers-color-scheme: dark).
Python (Media Query Emulation)
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()
    page.goto("https://example.com")

    # 1. Emulate Print Media Stylesheet
    page.emulate_media(media="print")
    is_print = page.evaluate("window.matchMedia('print').matches")
    print(f"Print Media Active: {is_print}")

    # 2. Emulate Dark Mode Color Scheme
    page.emulate_media(color_scheme="dark")
    is_dark = page.evaluate("window.matchMedia('(prefers-color-scheme: dark)').matches")
    print(f"Dark Mode Scheme Active: {is_dark}")

    # 3. Emulate Reduced Motion (Accessibility preference)
    page.emulate_media(reduced_motion="reduce")
    reduced_motion = page.evaluate("window.matchMedia('(prefers-reduced-motion: reduce)').matches")
    print(f"Reduced Motion Preference Active: {reduced_motion}")

    browser.close()
Output: Print Media Active: True Dark Mode Scheme Active: True Reduced Motion Preference Active: True
Real-Time Example 7: Responsive Navigation Hamburger Menu Validation
Verify responsive DOM transformations: assert that full desktop header navigation links are visible on wide screens, but collapse into a hamburger menu button on mobile viewports.
Python (Responsive Menu Assertion)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Load responsive HTML with media queries
    page.set_content("""
        
        
    """)

    # 1. Test Desktop Breakpoint (1280px wide)
    page.set_viewport_size({"width": 1280, "height": 720})
    expect(page.locator("#desktop-nav")).to_be_visible()
    expect(page.locator("#mobile-hamburger")).to_be_hidden()
    print("Desktop Viewport (1280px): Navigation links visible, hamburger button hidden.")

    # 2. Test Mobile Breakpoint (375px wide)
    page.set_viewport_size({"width": 375, "height": 667})
    expect(page.locator("#desktop-nav")).to_be_hidden()
    expect(page.locator("#mobile-hamburger")).to_be_visible()
    print("Mobile Viewport (375px)  : Navigation links collapsed, hamburger button visible.")

    browser.close()
Output: Desktop Viewport (1280px): Navigation links visible, hamburger button hidden. Mobile Viewport (375px) : Navigation links collapsed, hamburger button visible.
Real-Time Example 8: Parameterized Responsive Testing with Pytest
Combine Pytest parameterization with Playwright devices to run the exact same UI regression test suite automatically across multiple devices (Desktop, iPad, iPhone, Android).
Python (Pytest Device Matrix)
import pytest
from playwright.sync_api import sync_playwright

DEVICE_MATRIX = ["Desktop Chrome", "iPhone 13", "iPad Pro 11", "Pixel 7"]

def execute_device_test(device_name: str):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)

        if device_name == "Desktop Chrome":
            context = browser.new_context(viewport={"width": 1280, "height": 800})
        else:
            context = browser.new_context(**p.devices[device_name])

        page = context.new_page()
        page.goto("https://demo.playwright.dev/todomvc/")
        
        # Verify page renders and remains interactive across all devices
        todo_box = page.get_by_placeholder("What needs to be done?")
        todo_box.fill(f"Item on {device_name}")
        todo_box.press("Enter")

        count = page.locator(".todo-list li").count()
        print(f"Device [{device_name:15s}] -> 1 Item created successfully.")

        context.close()
        browser.close()

# Simulate Pytest parameterized execution loop
for dev in DEVICE_MATRIX:
    execute_device_test(dev)
Output: Device [Desktop Chrome ] -> 1 Item created successfully. Device [iPhone 13 ] -> 1 Item created successfully. Device [iPad Pro 11 ] -> 1 Item created successfully. Device [Pixel 7 ] -> 1 Item created successfully.
Real-Time Example 9: Viewport & Emulation Configuration Reference Table
A comprehensive reference matrix summarizing key emulation properties available in browser.new_context() and page.set_viewport_size().
Emulation Parameters Matrix
DEVICE EMULATION PROPERTIES MATRIX:
┌──────────────────────────────┬────────────────────────┬──────────────────────┬─────────────────────────────────────────────────────────┐
│ Property                     │ Type                   │ Default              │ Description / Use Case                                  │
├──────────────────────────────┼────────────────────────┼──────────────────────┼─────────────────────────────────────────────────────────┤
│ viewport                     │ Dict[str, int]         │ {"width": 1280, ...} │ Sets the browser viewport dimensions (width, height).   │
│ is_mobile                    │ bool                   │ False                │ Emulates meta viewport tags and mobile browser behavior.│
│ has_touch                    │ bool                   │ False                │ Enables TouchEvent API and touch gesture interactions.  │
│ device_scale_factor          │ float / int            │ 1                    │ Pixel density multiplier (e.g., 2 or 3 for Retina/OLED).│
│ user_agent                   │ str                    │ Default Engine UA    │ Emulates mobile/tablet User-Agent headers.              │
│ color_scheme                 │ str                    │ "no-preference"      │ Toggles CSS color modes: "light", "dark", "no-pref...". │
│ reduced_motion               │ str                    │ "no-preference"      │ Toggles accessibility preference: "reduce" or "no-pref".│
│ forced_colors                │ str                    │ "none"               │ Toggles high-contrast accessibility mode: "active".     │
│ page.set_viewport_size()     │ Dict[str, int]         │ Dynamic              │ Updates active viewport size on an existing page.       │
│ page.emulate_media()         │ kwargs                 │ Dynamic              │ Overrides media query types ("print", "screen").        │
└──────────────────────────────┴────────────────────────┴──────────────────────┴─────────────────────────────────────────────────────────┘
Summary: Playwright allows complete responsive and mobile device testing without external device clouds or third-party simulators.