new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Playwright · API reference · all subjects

browsercontext

119 notes in this subject, read out of this brain and free to use. This is page 2 of 2.

BrowserContext.route usage example

Example 1: Abort all image requests JavaScript: const context = await browser.newContext(); await context.route('**/*.{png,jpg,jpeg}', route => route.abort()); const page = await context.newPage(); await page.goto('https://example.com'); await browser.close(); Java: BrowserContext context = browser.newContext(); context.route("**/*.{png,jpg,jpeg}", route -> route.abort()); Page page = context.newPage(); page.navigate("https://example.com"); browser.close(); C#: var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); await context.RouteAsync("**/*.{png,jpg,jpeg}", r => r.AbortAsync()); await page.GotoAsync("https://theverge.com"); await browser.CloseAsync(); Example 2: Using regex pattern JavaScript: const context = await browser.newContext(); await context.route(/(\. png$)|(\. jpg$)/, route => route.abort()); const page = await context.newPage(); await page.goto('https://example.com'); await browser.close(); C#: var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); await context.RouteAsync(new Regex("(\\.png$)|(\\.jpg$)"), r => r.AbortAsync()); await page.GotoAsync("https://theverge.com"); await browser.CloseAsync(); Example 3: Examine request and mock based on post data JavaScript: await context.route('/api/**', async route => { if (route.request().postData().includes('my-string')) await route.fulfill({ body: 'mocked-data' }); else await route.continue(); }); Java: context.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); }); Python async: async def handle_route(route: Route): if ("my-string" in route.request.post_data): await route.fulfill(body="mocked-data") else: await route.continue_() await context.route("/api/**", handle_route) C#: await page.RouteAsync("/api/**", async r => { if (r.Request.PostData.Contains("my-string")) await r.FulfillAsync(new() { Body = "mocked-data" }); else await r.ContinueAsync(); });

BrowserContext.routeWebSocket usage example

Example of routing WebSocket connections to block certain messages: JavaScript: await context.routeWebSocket('/ws', async ws => { ws.routeSend(message => { if (message === 'to-be-blocked') return; ws.send(message); }); await ws.connect(); }); Java: context.routeWebSocket("/ws", ws -> { ws.routeSend(message -> { if ("to-be-blocked".equals(message)) return; ws.send(message); }); ws.connect(); }); Python async: def message_handler(ws: WebSocketRoute, message: Union[str, bytes]): if message == "to-be-blocked": return ws.send(message) async def handler(ws: WebSocketRoute): ws.route_send(lambda message: message_handler(ws, message)) await ws.connect() await context.route_web_socket("/ws", handler) C#: await context.RouteWebSocketAsync("/ws", async ws => { ws.RouteSend(message => { if (message == "to-be-blocked") return; ws.Send(message); }); await ws.ConnectAsync(); });

BrowserContext.setGeolocation usage example

Example of setting geolocation for a browser context: JavaScript: await browserContext.setGeolocation({ latitude: 59.95, longitude: 30.31667 }); Java: browserContext.setGeolocation(new Geolocation(59.95, 30.31667)); Python async: await browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667}) Python sync: browser_context.set_geolocation({"latitude": 59.95, "longitude": 30.31667}) C#: await context.SetGeolocationAsync(new Geolocation() { Latitude = 59.95f, Longitude = 30.31667f }); Note: Consider using BrowserContext.grantPermissions to grant permissions for pages to read geolocation.

BrowserContext.storageState usage example

Example of loading storage state from a file and applying it to the context: JavaScript: await context.setStorageState('state.json'); Java: context.setStorageState(Paths.get("state.json")); Python async: await context.set_storage_state("state.json") Python sync: context.set_storage_state("state.json") C#: await context.SetStorageStateAsync("state.json");

BrowserContext.waitForCondition usage example (Java)

Example of waiting for a condition that depends on page events: Java: List<String> failedUrls = new ArrayList<>(); context.onResponse(response -> { if (!response.ok()) { failedUrls.add(response.url()); } }); page1.getByText("Create user").click(); page2.getByText("Submit button").click(); context.waitForCondition(() -> failedUrls.size() > 3);

BrowserContext.waitForConsoleMessage usage example (Python)

Example of waiting for a console message in Python: Python async: async with context.expect_console_message() as message_info: await page.get_by_role("button").click() message = await message_info.value print(message.text) Python sync: with context.expect_console_message() as message_info: page.get_by_role("button").click() message = message_info.value print(message.text)

BrowserContext.waitForEvent usage example

Example of waiting for a page event: JavaScript: const pagePromise = context.waitForEvent('page'); await page.getByRole('button').click(); const page = await pagePromise; Java: Page newPage = context.waitForPage(() -> page.getByRole(AriaRole.BUTTON).click()); Python async: async with context.expect_event("page") as event_info: await page.get_by_role("button").click() page = await event_info.value Python sync: with context.expect_event("page") as event_info: page.get_by_role("button").click() page = event_info.value C#: var page = await context.RunAndWaitForPageAsync(async () => { await page.GetByRole(AriaRole.Button).ClickAsync(); });

BrowserContext.waitForPage usage example (Python)

Example of waiting for a new page in Python: Python async: async with context.expect_page() as page_info: await page.get_by_text("Open new tab").click() new_page = await page_info.value print(await new_page.title()) Python sync: with context.expect_page() as page_info: page.get_by_text("Open new tab").click() new_page = page_info.value print(new_page.title())

BrowserContext.page event example

Example of waiting for a new page and accessing its URL: JavaScript: const newPagePromise = context.waitForEvent('page'); await page.getByText('open new page').click(); const newPage = await newPagePromise; console.log(await newPage.evaluate('location.href')); Java: Page newPage = context.waitForPage(() -> { page.getByText("open new page").click(); }); System.out.println(newPage.evaluate("location.href")); Python async: async with context.expect_page() as page_info: await page.get_by_text("open new page").click(), page = await page_info.value print(await page.evaluate("location.href")) Python sync: with context.expect_page() as page_info: page.get_by_text("open new page").click(), page = page_info.value print(page.evaluate("location.href")) C#: var popup = await context.RunAndWaitForPageAsync(async => { await page.GetByText("open new page").ClickAsync(); }); Console.WriteLine(await popup.EvaluateAsync<string>("location.href"));

BrowserContext creation example

Example of creating a browser context, creating a page, navigating, and closing: JavaScript: const context = await browser.newContext(); const page = await context.newPage(); await page.goto('https://example.com'); await context.close(); Java: BrowserContext context = browser.newContext(); Page page = context.newPage(); page.navigate("https://example.com"); context.close(); Python async: context = await browser.new_context() page = await context.new_page() await page.goto("https://example.com") await context.close() Python sync: context = browser.new_context() page = context.new_page() page.goto("https://example.com") context.close() C#: var context = await browser.NewContextAsync(); var page = await context.NewPageAsync(); await page.GotoAsync("https://example.com"); await context.CloseAsync();

BrowserContext.grantPermissions() with origin parameter

The grantPermissions() method on browser context accepts an array of permission names as the first argument. It can accept an optional second argument with an origin property to grant permissions for a specific origin only. Example permission names include 'geolocation', 'notifications', 'camera', 'microphone', and 'clipboard-read'.

BrowserContext.setGeolocation() method signature

The setGeolocation() method accepts an object with latitude and longitude properties. Example: {latitude: 37.7749, longitude: -122.4194}.

BrowserContext.clearPermissions() method

The clearPermissions() method clears all permission grants and geolocation overrides set on the browser context.

BrowserContext.storageState() saves authentication state

The storageState() method accepts an options object with a path property. It saves the current storage state (cookies, local storage, session storage) to a file at the specified path.

context-option-contrast for JS and Java

The contrast parameter is null or Contrast ('no-preference', 'more'). Emulates prefers-contrast media feature. See Page.emulateMedia. Passing null resets. Defaults to 'no-preference'.

context-option-contrast for C# and Python

The contrast parameter is Contrast ('no-preference', 'more', 'null'). Emulates prefers-contrast media feature. Passing 'null' resets. Defaults to 'no-preference'.

csharp-context-option-viewport

The viewport parameter accepts null or Object (alias-csharp: viewportSize) with width (int, pixels) and height (int, pixels). Emulates consistent viewport. Defaults to 1280x720. Use ViewportSize.NoViewport to disable, opting out making viewport OS-dependent and non-deterministic.

js-python-context-option-storage-state structure

storageState accepts path or Object. Object contains: cookies (Array of {name, value, domain, path, expires, httpOnly, secure, sameSite}), origins (Array of {origin, localStorage (Array of {name, value})}). Used to populate context with storage state from BrowserContext.storageState.

csharp-java-context-option-storage-state and storage-state-path

For C# and Java: storageState parameter is type string. storageStatePath parameter is type path. Both populate context with storage state from BrowserContext.storageState.

storagestate-option-path: path parameter

The path parameter is type path. The file path to save storage state to. If relative, resolved relative to current working directory. If no path provided, state returned but not saved to disk.

context-option-acceptdownloads

The acceptDownloads parameter is type boolean. Whether to automatically download all attachments. Defaults to true where all downloads accepted.

context-option-ignorehttpserrors

The ignoreHTTPSErrors parameter is type boolean. Whether to ignore HTTPS errors when sending network requests. Defaults to false.

context-option-bypasscsp

The bypassCSP parameter is type boolean. Toggles bypassing page's Content-Security-Policy. Defaults to false.

context-option-baseURL

The baseURL parameter is type string. When using Page.goto, Page.route, Page.waitForURL, Page.waitForRequest, or Page.waitForResponse, takes base URL into consideration using URL constructor. Examples: baseURL 'http://localhost:3000' + '/bar.html' = 'http://localhost:3000/bar.html'; baseURL 'http://localhost:3000/foo/' + './bar.html' = 'http://localhost:3000/foo/bar.html'.

context-option-viewport for JS and Java

The viewport parameter accepts null or Object (alias: ViewportSize) with width (int, pixels) and height (int, pixels). Emulates consistent viewport for each page. Defaults to 1280x720. Use null to disable, opting out from defaults making viewport depend on OS window size, making tests non-deterministic.

context-option-screen: ScreenSize parameter

The screen parameter is type Object (alias: ScreenSize) with width (int, pixels) and height (int, pixels). Emulates consistent window screen size inside web page via window.screen. Only used when viewport is set.

python-context-option-viewport

The viewport parameter accepts null or Object with width (int, pixels) and height (int, pixels). Sets consistent viewport for each page. Defaults to 1280x720. noViewport disables fixed viewport. Refer to viewport emulation docs.

python-context-option-no-viewport: noViewport parameter

The noViewport parameter is type boolean. Does not enforce fixed viewport, allows resizing window in headed mode.

context-option-clientCertificates: TLS client authentication

The clientCertificates parameter is Array<Object> (alias: ClientCertificate). Each object has: origin (string, exact origin for cert), certPath/cert (path/Buffer for PEM certificate), keyPath/key (path/Buffer for PEM key), pfxPath/pfx (path/Buffer for PFX/PKCS12), passphrase (optional string). Each must have certPath+keyPath, pfxPath, cert+key, or pfx. Client cert auth active only when at least one cert provided.

context-option-useragent

The userAgent parameter is type string. Specific user agent to use in this context.

context-option-devicescalefactor

The deviceScaleFactor parameter is type float. Specify device scale factor (dpr). Defaults to 1. Refer to device emulation docs.

context-option-ismobile and context-option-hastouch

isMobile parameter type boolean: whether meta viewport tag taken into account and touch enabled. Part of device, not set manually. Defaults false, not Firefox-supported. hasTouch parameter type boolean: whether viewport supports touch events. Defaults false. Refer to mobile emulation docs.

context-option-javascriptenabled

The javaScriptEnabled parameter is type boolean. Whether to enable JavaScript in context. Defaults to true. Refer to disabling JavaScript docs.

context-option-timezoneid

The timezoneId parameter is type string. Changes context timezone. See ICU metaZones.txt for supported timezone IDs. Defaults to system timezone.

context-option-geolocation: Geolocation parameter

The geolocation parameter is type Object (alias: Geolocation) with: latitude (float, -90 to 90), longitude (float, -180 to 180), accuracy (optional float, non-negative, defaults to 0).

context-option-locale

The locale parameter is type string like 'en-GB' or 'de-DE'. Affects navigator.language, Accept-Language header, number/date formatting. Defaults to system locale. Refer to emulation guide.

context-option-permissions

The permissions parameter is type Array<string>. List of permissions to grant to all pages. See BrowserContext.grantPermissions. Defaults to none.

context-option-extrahttpheaders

The extraHTTPHeaders parameter is type Object<string, string>. Additional HTTP headers sent with every request. Defaults to none.

context-option-offline

The offline parameter is type boolean. Whether to emulate network being offline. Defaults to false. Refer to network emulation docs.

context-option-httpcredentials: HTTP authentication

The httpCredentials parameter is type Object or Array<Object> (alias: HttpCredentials) with: username (string), password (string), origin (optional string to restrict to specific origin), send (optional HttpCredentialsSend: 'unauthorized' or 'always'; only for APIRequestContext, not browser requests; 'always' sends Authorization header with each request, 'unauthorized' only when 401 received; defaults 'unauthorized'). If no origin, credentials sent on unauthorized responses. Pass array for different credentials per origin.

context-option-colorscheme for JS and Java

The colorScheme parameter is null or ColorScheme ('light', 'dark', 'no-preference'). Emulates prefers-color-scheme media feature. See Page.emulateMedia. Passing null resets. Defaults to 'light'.

context-option-colorscheme for C# and Python

The colorScheme parameter is ColorScheme ('light', 'dark', 'no-preference', 'null'). Emulates prefers-color-scheme media feature. Passing 'null' resets. Defaults to 'light'.

context-option-reducedMotion for JS and Java

The reducedMotion parameter is null or ReducedMotion ('reduce', 'no-preference'). Emulates prefers-reduced-motion media feature. See Page.emulateMedia. Passing null resets. Defaults to 'no-preference'.

context-option-reducedMotion for C# and Python

The reducedMotion parameter is ReducedMotion ('reduce', 'no-preference', 'null'). Emulates prefers-reduced-motion media feature. Passing 'null' resets. Defaults to 'no-preference'.

context-option-forcedColors for JS and Java

The forcedColors parameter is null or ForcedColors ('active', 'none'). Emulates forced-colors media feature. See Page.emulateMedia. Passing null resets. Defaults to 'none'.

context-option-forcedColors for C# and Python

The forcedColors parameter is ForcedColors ('active', 'none', 'null'). Emulates forced-colors media feature. Passing 'null' resets. Defaults to 'none'.

context-option-recordhar: HAR recording configuration

The recordHar parameter is Object with: omitContent (optional boolean, deprecated, use content instead), content (optional HarContentPolicy: 'omit', 'embed', 'attach'; defaults 'attach' for .zip, 'embed' otherwise), path (required path for HAR file), mode (optional HarMode: 'full', 'minimal'; defaults 'full'), urlFilter (optional string or RegExp to filter requests). Enables HAR recording to path. Await BrowserContext.close for save.

context-option-recordhar-path for C#, Java, Python

The recordHarPath parameter is type path (Python alias: record_har_path). Enables HAR recording to specified file. Call BrowserContext.close to save.

context-option-recordhar-omit-content for C#, Java, Python

The recordHarOmitContent parameter is optional boolean (Python alias: record_har_omit_content). Controls whether to omit request content from HAR. Defaults to false.

context-option-recordhar-content for C#, Java, Python

The recordHarContent parameter is optional HarContentPolicy ('omit', 'embed', 'attach') (Python alias: record_har_content). Controls resource content management. Defaults to 'embed'.

context-option-recordhar-mode for C#, Java, Python

The recordHarMode parameter is optional HarMode ('full', 'minimal') (Python alias: record_har_mode). Defaults to 'full'.

context-option-recordhar-url-filter for C#, Java, Python

The recordHarUrlFilter parameter is optional string or RegExp (Python alias: record_har_url_filter) to filter requests stored in HAR.

context-option-recordvideo: video recording configuration

The recordVideo parameter is Object with: dir (optional path for videos; defaults artifactsDir), size (optional Object with width and height; defaults viewport scaled to fit 800x800 or 800x450), showActions (optional Object with duration in ms default 500, position default 'top-right', fontSize default 24, cursor 'none' or 'pointer'). Enables video recording. Await BrowserContext.close to save.

context-option-recordvideo-dir for C#, Java, Python

The recordVideoDir parameter is type path (Python alias: record_video_dir). Enables video recording to directory. Call BrowserContext.close to save.

context-option-recordvideo-size for C#, Java, Python

The recordVideoSize parameter is Object (alias-java: RecordVideoSize) with width (int, pixels) and height (int, pixels). Dimensions of recorded videos. Defaults to viewport scaled to fit 800x800 or 800x450.

context-option-proxy for BrowserContext

The proxy parameter is Object (alias: Proxy) with: server (string, HTTP/SOCKS proxy), bypass (optional comma-separated domains), username (optional), password (optional). Defaults to none.

context-option-pierce-frames

The pierceFrames parameter is type boolean. If true, all selectors in context pierce frames by default as if created via Page.pierceFrames. Defaults to false.

context-option-strict: strictSelectors parameter

The strictSelectors parameter is type boolean. If true, enables strict selectors mode: operations on selectors throw when more than one element matches. Defaults to false. Locator APIs always strict.

context-option-service-worker-policy: serviceWorkers parameter

The serviceWorkers parameter is ServiceWorkerPolicy ('allow', 'block'). Whether to allow Service Worker registration. 'allow': can register. 'block': blocked. Defaults to 'allow'.

Give your agent this brain