Version: 1.10.0

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

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:

BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setUserAgent("My user agent"));

API reference#


Viewport#

Create a context with custom viewport size:

// Create context with given viewport
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setViewportSize(1280, 1024));
// Resize viewport for individual page
page.setViewportSize(1600, 1200);
// Emulate high-DPI
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setViewportSize(2560, 1440)
.setDeviceScaleFactor(2);

API reference#


Locale & timezone#

// Emulate locale and time
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setLocale("de-DE")
.setTimezoneId("Europe/Berlin"));

API reference#


Permissions#

Allow all pages in the context to show system notifications:

BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setPermissions(Arrays.asList("notifications"));

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

context.grantPermissions(Arrays.asList("geolocation"));

Grant notifications access from a specific domain:

context.grantPermissions(Arrays.asList("notifications"),
new BrowserContext.GrantPermissionsOptions().setOrigin("https://skype.com"));

Revoke all permissions:

context.clearPermissions();

API reference#


Geolocation#

Create a context with "geolocation" permissions granted:

BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setGeolocation(48.858455, 2.294474)
.setPermissions(Arrays.asList("geolocation")));

Change the location later:

context.setGeolocation(new Geolocation(29.979097, 31.134256));

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

API reference#


Color scheme and media#

Create a context with dark or light mode. Pages created in this context will follow this color scheme preference.

// Create context with dark mode
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setColorScheme(ColorScheme.DARK)); // or "light"
// Create page with dark mode
Page page = browser.newPage(new Browser.NewPageOptions()
.setColorScheme(ColorScheme.DARK)); // or "light"
// Change color scheme for the page
page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
// Change media for page
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));

API reference#