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 1 of 2.

BrowserContext class overview

BrowserContext provides a way to operate multiple independent browser sessions. If a page opens another page (e.g., with window.open), the popup belongs to the parent page's browser context. Non-persistent browser contexts created with Browser.newContext() do not write any browsing data to disk.

BrowserContext.clock property

The clock property is of type Clock. Playwright has the ability to mock clock and passage of time. Available since v1.45.

BrowserContext.credentials property

The credentials property is of type Credentials. It is a virtual WebAuthn authenticator for the context that lets tests seed credentials and intercept navigator.credentials.create() and navigator.credentials.get() ceremonies. Available since v1.61.

BrowserContext.debugger property

The debugger property is of type Debugger. It allows pausing and resuming execution. Available since v1.59.

BrowserContext.request property

The request property is of type APIRequestContext. It is an API testing helper associated with the context. Requests made with this API will use context cookies. Available since v1.16.

BrowserContext.tracing property

The tracing property is of type Tracing. Available since v1.12.

BrowserContext close event

The close event is emitted when a BrowserContext is closed. This might happen because: the browser context is closed, the browser application is closed or crashed, or Browser.close() was called. The event argument is the BrowserContext. Available since v1.8. The option parameter 'reason' (string) is available since v1.40 to report the reason to operations interrupted by context closure.

BrowserContext console event

The console event is emitted when JavaScript within the page calls a console API method (e.g., console.log or console.dir). The event argument is a ConsoleMessage. The arguments passed into console.log and the page are available on the ConsoleMessage event handler argument. Available since v1.34 (alias in Java: consoleMessage).

BrowserContext dialog event

The dialog event is emitted when a JavaScript dialog appears (alert, prompt, confirm, or beforeunload). The event argument is a Dialog. The listener must either call Dialog.accept() or Dialog.dismiss() on the dialog, otherwise the page will freeze waiting for the dialog and actions like click will never finish. Available since v1.34.

BrowserContext download event

The download event is emitted when attachment download started in any page belonging to the context. The event argument is a Download. Users can access basic file operations on downloaded content via the passed Download instance. See also Page.download to receive events about a specific page. Available since v1.60.

BrowserContext frameAttached event

The frameAttached event is emitted when a frame is attached in any page belonging to the context. The event argument is a Frame. See also Page.frameAttached to receive events about a specific page. Available since v1.60.

BrowserContext frameDetached event

The frameDetached event is emitted when a frame is detached in any page belonging to the context. The event argument is a Frame. See also Page.frameDetached to receive events about a specific page. Available since v1.60.

BrowserContext page event

The page event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event also fires for popup pages. The event argument is a Page. See also Page.popup to receive events about popups relevant to a specific page. The earliest moment a page is available is when it has navigated to the initial URL. Available since v1.8.

BrowserContext pageClose event

The pageClose event is emitted when a page in the context is closed. The event argument is a Page. See also Page.close to receive events about a specific page. Available since v1.60.

BrowserContext pageLoad event

The pageLoad event is emitted when the JavaScript load event is dispatched in any page belonging to the context. The event argument is a Page. See also Page.load to receive events about a specific page. Available since v1.60.

BrowserContext webError event

The webError event is emitted when an exception is unhandled in any of the pages in the context. The event argument is a WebError. To listen for errors from a particular page, use Page.pageError instead. Available since v1.38.

BrowserContext request event

The request event is emitted when a request is issued from any pages created through the context. The event argument is a Request (read-only). To listen for requests from a particular page, use Page.request. To intercept and mutate requests, use BrowserContext.route or Page.route. Available since v1.12.

BrowserContext response event

The response event is emitted when response status and headers are received for a request. The event argument is a Response. For a successful response, the sequence of events is: request, response, and requestFinished. To listen for response events from a particular page, use Page.response. Available since v1.12.

BrowserContext serviceWorker event

The serviceWorker event is emitted when a new service worker is created in the context. The event argument is a Worker. Service workers are only supported on Chromium-based browsers. Available since v1.11 (languages: js, python).

BrowserContext.addCookies method

async method: BrowserContext.addCookies adds cookies into the browser context. All pages within the context will have these cookies installed. Cookies can be obtained via BrowserContext.cookies. Available since v1.8. Parameter: cookies - Array of cookie objects (alias-java: Cookie), each containing: - name (string, required) - value (string, required) - url (string, optional) - Either url or both domain and path are required - domain (string, optional) - Prefix with dot for subdomains (e.g., ".example.com"). Either url or both domain and path are required - path (string, optional) - Either url or both domain and path are required - expires (float, optional) - Unix time in seconds - httpOnly (boolean, optional) - secure (boolean, optional) - sameSite (SameSiteAttribute<"Strict"|"Lax"|"None">, optional) - partitionKey (string, optional) - For partitioned third-party cookies (CHIPS), the partition key

BrowserContext.addInitScript method

async method: BrowserContext.addInitScript adds a script to be evaluated in the following scenarios: whenever a page is created in the browser context or navigated, and whenever a child frame is attached or navigated in any page in the browser context. The script is evaluated after the document was created but before any of its scripts were run. Returns a Disposable. Available since v1.8. The order of evaluation of multiple scripts installed via BrowserContext.addInitScript and Page.addInitScript is not defined. For JavaScript (param script): script parameter can be a function, string, or Object with optional 'path' (path to JavaScript file, relative paths resolved relative to current working directory) or 'content' (raw script content). Optional arg parameter passes an argument to the script (only when passing a function). For Java/C# (param script): script is a string or path. For Python: optional path parameter is the path to JavaScript file; optional script parameter is the raw script content. The exposeFunctions option (available since v1.62) is supported.

BrowserContext.backgroundPages method

method: BrowserContext.backgroundPages returns an Array of Pages. This method is deprecated since v1.11 because background pages have been removed from Chromium together with Manifest V2 extensions. Returns an empty list.

BrowserContext.browser method

method: BrowserContext.browser returns null or Browser. Gets the browser instance that owns the context. Returns null if the context is created outside of normal browser (e.g., Android or Electron). Available since v1.8.

BrowserContext.clearCookies method

async method: BrowserContext.clearCookies removes cookies from the context. Accepts optional filter. Available since v1.8. Options (available since v1.43): - name (string or RegExp, optional) - Only removes cookies with the given name - domain (string or RegExp, optional) - Only removes cookies with the given domain - path (string or RegExp, optional) - Only removes cookies with the given path

BrowserContext.clearPermissions method

async method: BrowserContext.clearPermissions clears all permission overrides for the browser context. Available since v1.8.

BrowserContext.close method

async method: BrowserContext.close closes the browser context. All pages that belong to the browser context will be closed. The default browser context cannot be closed. Available since v1.8.

BrowserContext.cookies method

async method: BrowserContext.cookies returns an Array of cookie objects (alias: Cookie, alias-csharp: BrowserContextCookiesResult). If no URLs are specified, returns all cookies. If URLs are specified, only cookies that affect those URLs are returned. Available since v1.8. Parameter: urls (optional) - string or Array of strings, optional list of URLs. Return value contains cookie objects with: - name (string) - value (string) - domain (string) - path (string) - expires (float) - Unix time in seconds - httpOnly (boolean) - secure (boolean) - sameSite (SameSiteAttribute<"Strict"|"Lax"|"None">) - partitionKey (string, optional)

BrowserContext.exposeFunction method

async method: BrowserContext.exposeFunction adds a function called 'name' on the window object of every frame in every page in the context. When called, executes the callback and returns a Promise resolving to the callback's return value. If the callback returns a Promise, it will be awaited. Returns a Disposable. Available since v1.8. Parameter: name (string) - Name of the function on the window object. Parameter: callback (function, alias: FunctionCallback) - Callback function that will be called in Playwright's context.

BrowserContext.grantPermissions method

async method: BrowserContext.grantPermissions grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified. Available since v1.8. Parameter: permissions (Array of strings, required) - A list of permissions to grant. Option: origin (string, optional) - The origin to grant permissions to (e.g., "https://example.com"). Supported permissions (may differ between browsers and versions): - 'accelerometer', 'ambient-light-sensor', 'background-sync', 'camera', 'clipboard-read', 'clipboard-write', 'geolocation', 'gyroscope', 'local-fonts', 'local-network-access', 'magnetometer', 'microphone', 'midi-sysex', 'midi', 'notifications', 'payment-handler', 'storage-access', 'screen-wake-lock'

BrowserContext.isClosed method

method: BrowserContext.isClosed returns a boolean indicating that the browser context is in the process of closing or has already been closed. Available since v1.59.

BrowserContext.newCDPSession method

async method: BrowserContext.newCDPSession returns a newly created CDPSession. CDP sessions are only supported on Chromium-based browsers. Available since v1.11. Parameter: page (Page or Frame, required) - Target to create new session for. For backwards-compatibility, this parameter is named 'page', but it can be a Page or Frame type.

BrowserContext.newPage method

async method: BrowserContext.newPage creates a new page in the browser context. Returns a Page. Available since v1.8.

BrowserContext.pages method

method: BrowserContext.pages returns an Array of Pages. Returns all open pages in the context. Available since v1.8.

BrowserContext.removeAllListeners method

async method: BrowserContext.removeAllListeners removes all listeners of the given type (or all registered listeners if no type given). Allows waiting for async listeners to complete or ignoring subsequent errors from these listeners. Available since v1.47 (languages: js). Parameter: type (string, optional) - The event type to remove listeners for. Option: behavior (see %%-remove-all-listeners-options-behavior-%%)

BrowserContext.route method

async method: BrowserContext.route enables routing that provides the capability to modify network requests made by any page in the browser context. Once enabled, every request matching the URL pattern will stall unless it is continued, fulfilled, or aborted. Returns a Disposable. Available since v1.8. Note: BrowserContext.route will not intercept requests intercepted by Service Worker. Disable Service Workers by setting Browser.newContext.serviceWorkers to 'block' when using request interception. Parameter: url (for js: string, RegExp, URLPattern, or function(URL):boolean; for python/csharp/java: string, RegExp, or function(URL):boolean) - A glob pattern, regex pattern, URL pattern, or predicate to match during routing. If Browser.newContext.baseURL is set and the URL is a string not starting with '*', it is resolved using new URL() constructor. Parameter: handler (for js/python: function(Route, Request): Promise<any>|any; for csharp/java: function(Route)) - Handler function to route the request. Option: times (integer, optional, since v1.15) - How often a route should be used. By default it will be used every time.

BrowserContext.routeFromHAR method

async method: BrowserContext.routeFromHAR serves network requests from a HAR file. Read more about Replaying from HAR. Available since v1.23. Note: Playwright will not serve requests intercepted by Service Worker from the HAR file. Disable Service Workers by setting Browser.newContext.serviceWorkers to 'block'. Parameter: har (path, required) - Path to a HAR file with prerecorded network data. If relative, resolved relative to current working directory. Options: - notFound (HarNotFound<"abort"|"fallback">, optional) - 'abort' aborts requests not found in HAR file; 'fallback' falls through to next route handler. Defaults to abort. - update (boolean, optional) - If specified, updates the HAR with actual network information instead of serving from file. File is written when BrowserContext.close() is called. - url (string or RegExp, required) - Glob pattern, regex, or predicate to match request URLs. Only matching requests served from HAR file. - updateMode (HarMode<"full"|"minimal">, optional, since v1.32) - 'minimal' records only routing information, omitting sizes, timing, etc. Defaults to 'minimal'. - updateContent (RouteFromHarUpdateContentPolicy<"embed"|"attach">, optional, since v1.32) - 'attach' persists resources as separate files/ZIP entries; 'embed' stores content inline.

BrowserContext.routeWebSocket method

async method: BrowserContext.routeWebSocket allows modifying WebSocket connections made by any page in the browser context. Only WebSockets created after this method is called will be routed. It is recommended to call this method before creating any pages. Available since v1.48. Parameter: url (string, RegExp, or function(URL):boolean) - Only WebSockets with URLs matching this pattern will be routed. String patterns can be relative to Browser.newContext.baseURL. Parameter: handler (for js/python: function(WebSocketRoute): Promise<any>|any; for csharp/java: function(WebSocketRoute)) - Handler function to route the WebSocket.

BrowserContext.serviceWorkers method

method: BrowserContext.serviceWorkers returns an Array of Workers. Service workers are only supported on Chromium-based browsers. Returns all existing service workers in the context. Available since v1.11 (languages: js, python).

BrowserContext.setDefaultTimeout method

method: BrowserContext.setDefaultTimeout sets the default maximum time for all methods accepting a timeout option. Available since v1.8. Note: Page.setDefaultNavigationTimeout, Page.setDefaultTimeout, and BrowserContext.setDefaultNavigationTimeout take priority over BrowserContext.setDefaultTimeout. Parameter: timeout (float, required) - Maximum time in milliseconds. Pass 0 to disable timeout.

BrowserContext.setExtraHTTPHeaders method

async method: BrowserContext.setExtraHTTPHeaders sets extra HTTP headers sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set via Page.setExtraHTTPHeaders. If a page overrides a header, the page-specific header value is used instead of the browser context header value. Available since v1.8. Note: BrowserContext.setExtraHTTPHeaders does not guarantee the order of headers in outgoing requests. Parameter: headers (Object<string, string>, required) - An object containing additional HTTP headers to be sent with every request. All header values must be strings.

BrowserContext.setGeolocation method

async method: BrowserContext.setGeolocation sets the context's geolocation. Passing null or undefined emulates position unavailable. Available since v1.8. Parameter: geolocation (null or Object, optional) - An object with: - latitude (float, required) - Latitude between -90 and 90 - longitude (float, required) - Longitude between -180 and 180 - accuracy (float, optional) - Non-negative accuracy value. Defaults to 0. Note: Consider using BrowserContext.grantPermissions to grant permissions for pages to read geolocation.

BrowserContext.setHTTPCredentials method

async method: BrowserContext.setHTTPCredentials sets HTTP credentials. Available since v1.8 (languages: js). This method is deprecated; browsers may cache credentials after successful authentication. Create a new browser context instead. Parameter: httpCredentials (null, Object, or Array of Objects, optional) - Each object contains: - username (string, required) - password (string, required) - origin (string, optional) - Restrain sending credentials on specific origin (scheme://host:port) Pass an array to use different credentials for different origins. The first entry matching the request origin is used; entries with no origin match any request.

BrowserContext.setOffline method

async method: BrowserContext.setOffline emulates network being offline for the browser context. Available since v1.8. Parameter: offline (boolean, required) - Whether to emulate network being offline for the browser context.

BrowserContext.storageState method

async method: BrowserContext.storageState returns storage state for the browser context. Returns an Object containing current cookies, local storage snapshot, IndexedDB snapshot, and virtual WebAuthn credentials. Available since v1.8. For JavaScript/Python: Returns Object with: - cookies (Array of Objects with: name, value, domain, path, expires (Unix time in seconds), httpOnly, secure, sameSite<"Strict"|"Lax"|"None">) - origins (Array of Objects with: origin (string), localStorage (Array of Objects with: name, value)) For C#/Java: Returns string. Options: - path (see %%-storagestate-option-path-%%) - File path to save storage state - indexedDB (boolean, optional, since v1.51) - Set to true to include IndexedDB in the storage state snapshot - credentials (boolean, optional, since v1.61) - Set to true to include the context's virtual WebAuthn credentials (passkeys). Captured credentials carry their private keys for re-seeding into later contexts. Restoring storage state with credentials automatically installs the virtual WebAuthn authenticator.

BrowserContext.setStorageState method

async method: BrowserContext.setStorageState clears existing cookies, local storage, IndexedDB entries, and virtual WebAuthn credentials, then sets new storage state. When storage state contains credentials, the virtual WebAuthn authenticator is installed (equivalent to Credentials.install), preventing real authenticators from working in the context. Available since v1.59. Parameter: storageState (for js/python) - Storage state from storage or file path (for csharp/java) - File path to storage state file.

BrowserContext.unroute method

async method: BrowserContext.unroute removes a route created with BrowserContext.route. When handler is not specified, removes all routes for the URL. Available since v1.8. Parameter: url (for js: string, RegExp, URLPattern, or function(URL):boolean; for python/csharp/java: string, RegExp, or function(URL):boolean) - A glob pattern, regex pattern, URL pattern, or predicate receiving URL used to register routing with BrowserContext.route. Parameter: handler (for js/python: optional function(Route, Request): Promise<any>|any; for csharp/java: optional function(Route)) - Optional handler function used to register routing with BrowserContext.route.

BrowserContext.unrouteAll method

async method: BrowserContext.unrouteAll removes all routes created with BrowserContext.route and BrowserContext.routeFromHAR. Available since v1.41. Option: behavior (see %%-unroute-all-options-behavior-%%) - Controls behavior when unrouting.

BrowserContext.waitForCondition method

async method: BrowserContext.waitForCondition blocks until the condition returns true. All Playwright events are dispatched while waiting. Available since v1.32 (languages: java). Parameter: condition (BooleanSupplier, required) - Condition to wait for. Option: timeout (see %%-wait-for-function-timeout-%%) - Maximum time to wait.

BrowserContext.addCookies usage example

Example of adding cookies to a BrowserContext: JavaScript: await browserContext.addCookies([cookieObject1, cookieObject2]); Java: browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2)); Python async: await browser_context.add_cookies([cookie_object1, cookie_object2]) Python sync: browser_context.add_cookies([cookie_object1, cookie_object2]) C#: await context.AddCookiesAsync(new[] { cookie1, cookie2 });

BrowserContext.waitForConsoleMessage method

async method: BrowserContext.waitForConsoleMessage performs action and waits for a ConsoleMessage to be logged in pages in the context. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return truthy. Throws error if page closes before the console event fires. Available since v1.34 (languages: java, python, csharp with aliases: expect_console_message (python), RunAndWaitForConsoleMessage (csharp)). For python: Returns EventContextManager<ConsoleMessage>. Parameter: action (for csharp, see %%-csharp-wait-for-event-action-%%) - Action to perform. Option: predicate (function(ConsoleMessage):boolean, optional) - Receives ConsoleMessage and resolves to truthy when waiting should resolve. Option: timeout (see %%-wait-for-event-timeout-%%) - Maximum time to wait. Option: signal (see %%-wait-for-event-signal-%%) - Signal for cancellation.

BrowserContext.waitForEvent2 method (Python alternative)

async method: BrowserContext.waitForEvent2 waits for a given event to fire. If predicate is provided, it passes event value into the predicate function and waits for predicate(event) to return truthy. Throws error if browser context closes before event fires. Available since v1.8 (languages: python with alias: wait_for_event). Note: In most cases, use BrowserContext.waitForEvent instead. Parameter: event (see %%-wait-for-event-event-%%) - Event to wait for. Option: predicate (see %%-wait-for-event-predicate-%%) - Predicate function. Option: timeout (see %%-wait-for-event-timeout-%%) - Maximum time to wait. Option: signal (see %%-wait-for-event-signal-%%) - Signal for cancellation.

BrowserContext.waitForPage method

async method: BrowserContext.waitForPage performs action and waits for a new Page to be created in the context. If predicate is provided, it passes Page value into the predicate function and waits for predicate(event) to return truthy. Throws error if context closes before new Page is created. Available since v1.9 (languages: java, python, csharp with aliases: expect_page (python), RunAndWaitForPage (csharp)). For python: Returns EventContextManager<Page>. Parameter: action (for csharp, since v1.12, see %%-csharp-wait-for-event-action-%%) - Action to perform. Option: predicate (function(Page):boolean, optional, since v1.9, languages: csharp, java, python) - Receives Page object and resolves to truthy when waiting should resolve. Option: timeout (see %%-wait-for-event-timeout-%%, since v1.9) - Maximum time to wait. Option: signal (see %%-wait-for-event-signal-%%) - Signal for cancellation. Parameter: callback (see %%-java-wait-for-event-callback-%%, since v1.9, languages: java) - Callback function.

BrowserContext.backgroundPage event deprecated

The backgroundPage event (since v1.11) is deprecated. Background pages have been removed from Chromium together with Manifest V2 extensions. This event is not emitted. The event argument is a Page.

BrowserContext console event example

Example of handling console messages in BrowserContext: JavaScript: context.on('console', async msg => { const values = []; for (const arg of msg.args()) values.push(await arg.jsonValue()); console.log(...values); }); await page.evaluate(() => console.log('hello', 5, { foo: 'bar' })); Python async: async def print_args(msg): values = [] for arg in msg.args: values.append(await arg.json_value()) print(values) context.on("console", print_args) await page.evaluate("console.log('hello', 5, { foo: 'bar' })") C#: context.Console += async (_, msg) => { foreach (var arg in msg.Args) Console.WriteLine(await arg.JsonValueAsync<object>()); }; await page.EvaluateAsync("console.log('hello', 5, { foo: 'bar' })");

BrowserContext dialog event handling example

Example of handling dialog in BrowserContext: JavaScript: context.on('dialog', dialog => { dialog.accept(); }); Java: context.onDialog(dialog -> { dialog.accept(); }); Python: context.on("dialog", lambda dialog: dialog.accept()) C#: Context.Dialog += async (_, dialog) => { await dialog.AcceptAsync(); }; Note: When no Page.dialog or BrowserContext.dialog listeners are present, all dialogs are automatically dismissed.

BrowserContext.addInitScript usage example

Example of adding an init script to override Math.random before page loads: preload.js: Math.random = () => 42; Playwright script (assuming preload.js in same directory): JavaScript: await browserContext.addInitScript({ path: 'preload.js' }); Java: browserContext.addInitScript(Paths.get("preload.js")); Python async: await browser_context.add_init_script(path="preload.js") Python sync: browser_context.add_init_script(path="preload.js") C#: await Context.AddInitScriptAsync(scriptPath: "preload.js");

BrowserContext.clearCookies usage example

Example of clearing cookies from a BrowserContext: JavaScript: await context.clearCookies(); await context.clearCookies({ name: 'session-id' }); await context.clearCookies({ domain: 'my-origin.com' }); await context.clearCookies({ domain: /.*my-origin\.com/ }); await context.clearCookies({ path: '/api/v1' }); await context.clearCookies({ name: 'session-id', domain: 'my-origin.com' }); Java: context.clearCookies(); context.clearCookies(new BrowserContext.ClearCookiesOptions().setName("session-id")); context.clearCookies(new BrowserContext.ClearCookiesOptions().setDomain("my-origin.com")); context.clearCookies(new BrowserContext.ClearCookiesOptions().setPath("/api/v1")); context.clearCookies(new BrowserContext.ClearCookiesOptions() .setName("session-id") .setDomain("my-origin.com")); Python async: await context.clear_cookies() await context.clear_cookies(name="session-id") await context.clear_cookies(domain="my-origin.com") await context.clear_cookies(path="/api/v1") await context.clear_cookies(name="session-id", domain="my-origin.com") C#: await context.ClearCookiesAsync(); await context.ClearCookiesAsync(new() { Name = "session-id" }); await context.ClearCookiesAsync(new() { Domain = "my-origin.com" }); await context.ClearCookiesAsync(new() { Path = "/api/v1" }); await context.ClearCookiesAsync(new() { Name = "session-id", Domain = "my-origin.com" });

BrowserContext.clearPermissions usage example

Example of clearing permissions: JavaScript: const context = await browser.newContext(); await context.grantPermissions(['clipboard-read']); // do stuff .. context.clearPermissions(); Java: BrowserContext context = browser.newContext(); context.grantPermissions(Arrays.asList("clipboard-read")); // do stuff .. context.clearPermissions(); Python async: context = await browser.new_context() await context.grant_permissions(["clipboard-read"]) # do stuff .. context.clear_permissions() Python sync: context = browser.new_context() context.grant_permissions(["clipboard-read"]) # do stuff .. context.clear_permissions() C#: var context = await browser.NewContextAsync(); await context.GrantPermissionsAsync(new[] { "clipboard-read" }); // Alternatively, you can use the helper class ContextPermissions // to specify the permissions... // do stuff ... await context.ClearPermissionsAsync();

BrowserContext.exposeBinding usage example

Example of exposing page URL to all frames in all pages in the context: JavaScript: const { webkit } = require('playwright'); (async () => { const browser = await webkit.launch({ headless: false }); const context = await browser.newContext(); await context.exposeBinding('pageURL', ({ page }) => page.url()); const page = await context.newPage(); await page.setContent(` <script> async function onClick() { document.querySelector('div').textContent = await window.pageURL(); } </script> <button onclick="onClick()">Click me</button> <div></div> `); await page.getByRole('button').click(); })(); C#: using Microsoft.Playwright; using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Webkit.LaunchAsync(new() { Headless = false }); var context = await browser.NewContextAsync(); await context.ExposeBindingAsync("pageURL", source => source.Page.Url); var page = await context.NewPageAsync(); await page.SetContentAsync("<script>\n" + " async function onClick() {\n" + " document.querySelector('div').textContent = await window.pageURL();\n" + " }\n" + "</script>\n" + "<button onclick=\"onClick()\">Click me</button>\n" + "<div></div>"); await page.GetByRole(AriaRole.Button).ClickAsync();

BrowserContext.exposeFunction usage example

Example of exposing a sha256 function to all pages in the context: JavaScript: const { webkit } = require('playwright'); const crypto = require('crypto'); (async () => { const browser = await webkit.launch({ headless: false }); const context = await browser.newContext(); await context.exposeFunction('sha256', text => crypto.createHash('sha256').update(text).digest('hex'), ); const page = await context.newPage(); await page.setContent(` <script> async function onClick() { document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT'); } </script> <button onclick="onClick()">Click me</button> <div></div> `); await page.getByRole('button').click(); })(); C#: using Microsoft.Playwright; using System; using System.Security.Cryptography; using System.Threading.Tasks; class BrowserContextExamples { public static async Task Main() { using var playwright = await Playwright.CreateAsync(); var browser = await playwright.Webkit.LaunchAsync(new() { Headless = false }); var context = await browser.NewContextAsync(); await context.ExposeFunctionAsync("sha256", (string input) => { return Convert.ToBase64String( SHA256.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(input))); }); var page = await context.NewPageAsync(); await page.SetContentAsync("<script>\n" + " async function onClick() {\n" + " document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" + " }\n" + "</script>\n" + "<button onclick=\"onClick()\">Click me</button>\n" + "<div></div>"); await page.GetByRole(AriaRole.Button).ClickAsync(); Console.WriteLine(await page.TextContentAsync("div")); } }

Give your agent this brain