YouTip LogoYouTip

Playwright Emulation

This chapter introduces how to emulate browser environment parameters in Playwright, such as mobile devices, geolocation, timezones, languages, and color schemes. * * * ## Mobile Device Emulation Playwright comes with built-in device presets that can emulate the viewport, User-Agent, and touch behavior of various phones and tablets. ### Using devices Presets You can quickly emulate a specific device using the `devices` object. ## Example import{ chromium, devices } from 'playwright'; // Emulate iPhone 15 const browser = await chromium.launch(); const context = await browser.newContext(devices['iPhone 15']); const page = await context.newPage(); await page.goto(''); // The page will render with iPhone 15's viewport and UA 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 also manually specify the viewport size. ## Example const context = await browser.newContext({ viewport:{ width:375, height:812},// Viewport size deviceScaleFactor:3,// Device pixel ratio (Retina display) isMobile:true,// Enable mobile mode hasTouch:true,// Enable touch emulation userAgent:'Mozilla/5.0 ... Mobile ...',// Custom UA }); * * * ## Geolocation Emulation Playwright can emulate the GPS location information of a device. ## Example test('Emulate 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(''); // The page will get the location information for Beijing }); * * * ## Timezone and Language Emulation Verify internationalization and timezone-related features by setting the 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: | 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 test the effects of the `prefers-color-scheme` media query. ## 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 Use `context.grantPermissions()` to grant browser permissions. ## Example await context.grantPermissions([ 'geolocation',// Geolocation 'notifications',// Notifications 'camera',// Camera 'microphone',// Microphone 'clipboard-read',// Read clipboard 'clipboard-write',// Write clipboard ]); // Clear all permissions await context.clearPermissions(); * * * ## Cookie Operations You can read, add, and clear cookies through BrowserContext. ## Example // Add Cookie await context.addCookies([ { name:'tutorial_session', value:'session_token_value', domain:'www.', 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(''); // Clear all Cookies await context.clearCookies(); ### Cookie Parameter Description | Field | Type | Description | | --- | --- | --- | | `name` | string | Cookie name | | `value` | string | Cookie value | | `domain` | string | Effective domain | | `path` | string | Effective path, default `'/'` | | `expires` | number | Expiration time (Unix timestamp) | | `httpOnly` | boolean | Whether it is accessible only via HTTP | | `secure` | boolean | Whether it is transmitted only via HTTPS | | `sameSite` | string | SameSite policy: `'Strict'` | `'Lax'` | `'None'` | * * * ## localStorage and SessionStorage Operations Operate storage within the page context using `page.evaluate()`. ## Example // Set localStorage await page.evaluate(()=>{ localStorage.setItem('tutorial_key','tutorial_value'); }); // Read localStorage const value = await page.evaluate(()=>{ return localStorage.getItem('tutorial_key'); }); console.log(value);// 'tutorial_value' // Clear localStorage await page.evaluate(()=>{ localStorage.clear(); }); > Cookie and Storage operations should be completed before `page.goto()` to ensure that the data is available when the page loads.
← Playwright FramePlaywright Screenshots Videos β†’