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
// 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
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
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
// 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
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:
| locale | Language/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
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
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
'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
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
| Field | Type | Description |
|---|---|---|
name | string | Cookie name |
value | string | Cookie value |
domain | string | Domain for which it takes effect |
path | string | Path for which it takes effect, default'/' |
expires | number | Expiration time (Unix timestamp) |
httpOnly | boolean | Whether it is HTTP-only |
secure | boolean | Whether it is transmitted over HTTPS only |
sameSite | string | SameSite policy:'Strict' | 'Lax' | 'None' |
localStorage and SessionStorage Operations
Throughpage.evaluate()operate on storage in the page context.
Example
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();
});
Other ExtensionsCookie and Storage operations should be done before
page.goto()to ensure this data is available when the page loads.