Device and environment emulation

Playwright allows overriding various parameters of the device where the browser is running:

  • viewport size, device scale factor, touch support
  • locale, timezone
  • color scheme
  • geolocation
  • etc

Most of these parameters are configured during the browser context construction, but some of them such as viewport size can be changed for individual pages.

User agent

All pages created in the context above will share the user agent specified:

  1. const context = await browser.newContext({
  2. userAgent: 'My user agent'
  3. });

API reference

Viewport, color scheme

Create a context with custom viewport size:

  1. // Create context with given viewport
  2. const context = await browser.newContext({
  3. viewport: { width: 1280, height: 1024 }
  4. });
  5. // Resize viewport for individual page
  6. await page.setViewportSize({ width: 1600, height: 1200 });
  7. // Emulate high-DPI
  8. const context = await browser.newContext({
  9. viewport: { width: 2560, height: 1440 },
  10. deviceScaleFactor: 2,
  11. });
  12. // Create device with the dark color scheme:
  13. const context = await browser.newContext({
  14. colorScheme: 'dark'
  15. });
  16. // Change color scheme for the page
  17. await page.emulateMedia({ colorScheme: 'dark' });

API reference

Devices

Playwright comes with a registry of device parameters for selected mobile devices. It can be used to simulate browser behavior on a mobile device:

  1. const { chromium, devices } =
  2. require('playwright');
  3. const browser = await chromium.launch();
  4. const pixel2 = devices['Pixel 2'];
  5. const context = await browser.newContext({
  6. ...pixel2,
  7. });

All pages created in the context above will share the same device parameters.

API reference

Locale & timezone

  1. // Emulate locale and time
  2. const context = await browser.newContext({
  3. locale: 'de-DE',
  4. timezoneId: 'Europe/Berlin',
  5. });

API reference

Permissions

Allow all pages in the context to show system notifications:

  1. const context = await browser.newContext({
  2. permissions: ['notifications'],
  3. });

Grant all pages in the existing context access to current location:

  1. await context.grantPermissions(['geolocation']);

Grant notifications access from a specific domain:

  1. await context.grantPermissions(['notifications'], {origin: 'https://skype.com'} );

Revoke all permissions:

  1. await context.clearPermissions();

API reference

Geolocation

Create a context with "geolocation" permissions granted:

  1. const context = await browser.newContext({
  2. geolocation: { longitude: 48.858455, latitude: 2.294474 },
  3. permissions: ['geolocation']
  4. });

Change the location later:

  1. await context.setGeolocation({ longitude: 29.979097, latitude: 31.134256 });

Note you can only change geolocation for all pages in the context.

API reference