Playwright Device and Browser Emulation

This chapter introduces how to simulate browser environment parameters such as mobile devices, geolocation, timezone, language, and color scheme in Playwright.


Mobile Device Emulation

Playwright has a large number of built-in device presets that can simulate the viewport, User-Agent, and touch behavior of various phones and tablets.

Using the devices Preset

Using thedevicesobject, you can quickly simulate a specific device.

Example

import { chromium, devices } from 'playwright';

// Simulate iPhone 15
const browser = await chromium.launch();
const context = await browser.newContext(devices['iPhone 15']);
const page = await context.newPage();

await page.goto('https://www.example.com/');
// The page will render with the viewport and UA of iPhone 15

Using device presets in the configuration file:

Example

// File path: playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'mobile',
      use: { ...devices['Pixel 7'] },
    },
  ],
});

Manually Configuring the Viewport

If you don't need a complete device preset, you can manually specify the viewport size.

Example

const context = await browser.newContext({
  viewport: { width: 375, height: 812 },     // Viewport size
  deviceScaleFactor: 3,                       // Device pixel ratio (Retina screen)
  isMobile: true,                             // Enable mobile mode
  hasTouch: true,                             // Enable touch emulation
  userAgent: 'Mozilla/5.0 ... Mobile ...',    // Custom UA
});

Geolocation Emulation

Playwright can simulate the device's GPS location information.

Example

test('Simulate Beijing location', async ({ context, page }) => {
  // Grant geolocation permission
  await context.grantPermissions(['geolocation']);

  // Set specific latitude and longitude (Beijing coordinates)
  await context.setGeolocation({
    latitude: 39.9042,
    longitude: 116.4074,
  });

  await page.goto('https://www.example.com/map');
  // The page will get the location information of Beijing
});

Timezone and Language Emulation

Verify internationalization and timezone-related functionality by setting locale and timezone.

Example

const context = await browser.newContext({
  locale: 'zh-CN',                // Set browser language to Simplified Chinese
  timezone: 'Asia/Shanghai',      // Set timezone to Shanghai (UTC+8)
});

// Set globally in the configuration file
export default defineConfig({
  use: {
    locale: 'en-US',
    timezone: 'America/New_York',
  },
});

Common locale values:

localeLanguage/Region
'zh-CN'Simplified Chinese (China)
'zh-TW'Traditional Chinese (Taiwan)
'en-US'English (United States)
'ja-JP'Japanese
'ko-KR'Korean

Color Scheme Emulation

Emulate light or dark mode to testprefers-color-schemethe effect of media queries.

Example

// Test dark mode
const darkContext = await browser.newContext({
  colorScheme: 'dark',
});

// Possible values: 'light', 'dark', 'no-preference'

Set different color schemes for different projects in the configuration file:

Example

// File path: playwright.config.ts
export default defineConfig({
  projects: [
    {
      name: 'chromium-light',
      use: { colorScheme: 'light' },
    },
    {
      name: 'chromium-dark',
      use: { colorScheme: 'dark' },
    },
  ],
});

Permission Emulation

Usecontext.grantPermissions()to grant browser permissions.

Example

await context.grantPermissions([
  'geolocation',        // Geolocation
  'notifications',      // Notifications
  'camera',             // Camera
  'microphone',         // Microphone
  'clipboard-read',     // Read clipboard
  'clipboard-write',    // Write to clipboard
]);

// Clear all permissions
await context.clearPermissions();

Cookie Operations

Through BrowserContext, you can read, add, and clear Cookies.

Example

// Add Cookie
await context.addCookies([
  {
    name: 'example_session',
    value: 'session_token_value',
    domain: 'www.example.com',
    path: '/',
    httpOnly: true,
    secure: true,
    sameSite: 'Lax',
  },
]);

// Get all Cookies
const cookies = await context.cookies();
console.log(cookies);

// Get Cookies for a specific URL
const siteCookies = await context.cookies('https://www.example.com');

// Clear all Cookies
await context.clearCookies();

Cookie Parameter Description

FieldTypeDescription
namestringCookie name
valuestringCookie value
domainstringDomain for which it takes effect
pathstringPath for which it takes effect, default'/'
expiresnumberExpiration time (Unix timestamp)
httpOnlybooleanWhether it is HTTP-only
securebooleanWhether it is transmitted over HTTPS only
sameSitestringSameSite policy:'Strict' | 'Lax' | 'None'

localStorage and SessionStorage Operations

Throughpage.evaluate()operate on storage in the page context.

Example

// Set localStorage
await page.evaluate(() => {
  localStorage.setItem('example_key', 'example_value');
});

// Read localStorage
const value = await page.evaluate(() => {
  return localStorage.getItem('example_key');
});
console.log(value); // 'example_value'

// Clear localStorage
await page.evaluate(() => {
  localStorage.clear();
});

Cookie and Storage operations should be done beforepage.goto()to ensure this data is available when the page loads.

Other Extensions