A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://playwright.dev/java/docs/api/class-browsercontext below:

BrowserContext | Playwright Java

BrowserContext

BrowserContexts provide a way to operate multiple independent browser sessions.

If a page opens another page, e.g. with a window.open call, the popup will belong to the parent page's browser context.

Playwright allows creating isolated non-persistent browser contexts with Browser.newContext() method. Non-persistent browser contexts don't write any browsing data to disk.


BrowserContext context = browser.newContext();

Page page = context.newPage();
page.navigate("https://example.com");

context.close();
Methods addCookiesAdded before v1.9 browserContext.addCookies

Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via BrowserContext.cookies().

Usage

browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));

Arguments

Returns

addInitScriptAdded before v1.9 browserContext.addInitScript

Adds a script which would be evaluated in one of the following scenarios:

The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

Usage

An example of overriding Math.random before the page loads:


browserContext.addInitScript(Paths.get("preload.js"));

Arguments

Returns

backgroundPagesAdded in: v1.11 browserContext.backgroundPages

note

Background pages are only supported on Chromium-based browsers.

All existing background pages in the context.

Usage

BrowserContext.backgroundPages();

Returns

browserAdded before v1.9 browserContext.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.

Usage

BrowserContext.browser();

Returns

clearCookiesAdded before v1.9 browserContext.clearCookies

Removes cookies from context. Accepts optional filter.

Usage

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"));

Arguments

Returns

clearPermissionsAdded before v1.9 browserContext.clearPermissions

Clears all permission overrides for the browser context.

Usage

BrowserContext context = browser.newContext();
context.grantPermissions(Arrays.asList("clipboard-read"));

context.clearPermissions();

Returns

closeAdded before v1.9 browserContext.close

Closes the browser context. All the pages that belong to the browser context will be closed.

note

The default browser context cannot be closed.

Usage

BrowserContext.close();
BrowserContext.close(options);

Arguments

Returns

cookiesAdded before v1.9 browserContext.cookies

If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.

Usage

BrowserContext.cookies();
BrowserContext.cookies(urls);

Arguments

Returns

exposeBindingAdded before v1.9 browserContext.exposeBinding

The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.

The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

See Page.exposeBinding() for page-only version.

Usage

An example of exposing page URL to all frames in all pages in the context:

import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext context = browser.newContext();
context.exposeBinding("pageURL", (source, args) -> source.page().url());
Page page = context.newPage();
page.setContent("<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>");
page.getByRole(AriaRole.BUTTON).click();
}
}
}

Arguments

Returns

exposeFunctionAdded before v1.9 browserContext.exposeFunction

The method adds a function called name on the window object of every frame in every page in the context. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

If the callback returns a Promise, it will be awaited.

See Page.exposeFunction() for page-only version.

Usage

An example of adding a sha256 function to all pages in the context:

import com.microsoft.playwright.*;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType webkit = playwright.webkit();
Browser browser = webkit.launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext context = browser.newContext();
context.exposeFunction("sha256", args -> {
String text = (String) args[0];
MessageDigest crypto;
try {
crypto = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
return null;
}
byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(token);
});
Page page = context.newPage();
page.setContent("<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>\n");
page.getByRole(AriaRole.BUTTON).click();
}
}
}

Arguments

Returns

grantPermissionsAdded before v1.9 browserContext.grantPermissions

Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.

Usage

BrowserContext.grantPermissions(permissions);
BrowserContext.grantPermissions(permissions, options);

Arguments

Returns

newCDPSessionAdded in: v1.11 browserContext.newCDPSession

note

CDP sessions are only supported on Chromium-based browsers.

Returns the newly created session.

Usage

BrowserContext.newCDPSession(page);

Arguments

Returns

newPageAdded before v1.9 browserContext.newPage

Creates a new page in the browser context.

Usage

BrowserContext.newPage();

Returns

pagesAdded before v1.9 browserContext.pages

Returns all open pages in the context.

Usage

Returns

routeAdded before v1.9 browserContext.route

Routing provides the capability to modify network requests that are made by any page in the browser context. Once route is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

Usage

An example of a naive handler that aborts all image requests:

BrowserContext context = browser.newContext();
context.route("**/*.{png,jpg,jpeg}", route -> route.abort());
Page page = context.newPage();
page.navigate("https://example.com");
browser.close();

or the same snippet using a regex pattern instead:

BrowserContext context = browser.newContext();
context.route(Pattern.compile("(\\.png$)|(\\.jpg$)"), route -> route.abort());
Page page = context.newPage();
page.navigate("https://example.com");
browser.close();

It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

context.route("/api/**", route -> {
if (route.request().postData().contains("my-string"))
route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
else
route.resume();
});

Page routes (set up with Page.route()) take precedence over browser context routes when request matches both handlers.

To remove a route with its handler you can use BrowserContext.unroute().

note

Enabling routing disables http cache.

Arguments

Returns

routeFromHARAdded in: v1.23 browserContext.routeFromHAR

If specified the network requests that are made in the context will be served from the HAR file. Read more about Replaying from HAR.

Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting setServiceWorkers to 'block'.

Usage

BrowserContext.routeFromHAR(har);
BrowserContext.routeFromHAR(har, options);

Arguments

Returns

routeWebSocketAdded in: v1.48 browserContext.routeWebSocket

This method allows to modify websocket connections that are made by any page in the browser context.

Note that only WebSockets created after this method was called will be routed. It is recommended to call this method before creating any pages.

Usage

Below is an example of a simple handler that blocks some websocket messages. See WebSocketRoute for more details and examples.

context.routeWebSocket("/ws", ws -> {
ws.routeSend(message -> {
if ("to-be-blocked".equals(message))
return;
ws.send(message);
});
ws.connect();
});

Arguments

Returns

setDefaultNavigationTimeoutAdded before v1.9 browserContext.setDefaultNavigationTimeout

This setting will change the default maximum navigation time for the following methods and related shortcuts:

Usage

BrowserContext.setDefaultNavigationTimeout(timeout);

Arguments

setDefaultTimeoutAdded before v1.9 browserContext.setDefaultTimeout

This setting will change the default maximum time for all the methods accepting timeout option.

Usage

BrowserContext.setDefaultTimeout(timeout);

Arguments

Added before v1.9 browserContext.setExtraHTTPHeaders

The extra HTTP headers will be sent with every request initiated by any page in the context. These headers are merged with page-specific extra HTTP headers set with Page.setExtraHTTPHeaders(). If page overrides a particular header, page-specific header value will be used instead of the browser context header value.

Usage

BrowserContext.setExtraHTTPHeaders(headers);

Arguments

Returns

setGeolocationAdded before v1.9 browserContext.setGeolocation

Sets the context's geolocation. Passing null or undefined emulates position unavailable.

Usage

browserContext.setGeolocation(new Geolocation(59.95, 30.31667));

Arguments

Returns

setOfflineAdded before v1.9 browserContext.setOffline

Usage

BrowserContext.setOffline(offline);

Arguments

Returns

storageStateAdded before v1.9 browserContext.storageState

Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.

Usage

BrowserContext.storageState();
BrowserContext.storageState(options);

Arguments

Returns

unrouteAdded before v1.9 browserContext.unroute

Removes a route created with BrowserContext.route(). When handler is not specified, removes all routes for the url.

Usage

BrowserContext.unroute(url);
BrowserContext.unroute(url, handler);

Arguments

Returns

unrouteAllAdded in: v1.41 browserContext.unrouteAll

Removes all routes created with BrowserContext.route() and BrowserContext.routeFromHAR().

Usage

BrowserContext.unrouteAll();

Returns

waitForConditionAdded in: v1.32 browserContext.waitForCondition

The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.

Usage

Use the method to wait for a condition that depends on page events:

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);

Arguments

Returns

waitForConsoleMessageAdded in: v1.34 browserContext.waitForConsoleMessage

Performs action and waits for a ConsoleMessage to be logged by in the pages in the context. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the BrowserContext.onConsoleMessage(handler) event is fired.

Usage

BrowserContext.waitForConsoleMessage(callback);
BrowserContext.waitForConsoleMessage(callback, options);

Arguments

Returns

waitForPageAdded in: v1.9 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 a truthy value. Will throw an error if the context closes before new Page is created.

Usage

BrowserContext.waitForPage(callback);
BrowserContext.waitForPage(callback, options);

Arguments

Returns

Properties clock()Added in: v1.45 browserContext.clock()

Playwright has ability to mock clock and passage of time.

Usage

Returns

request()Added in: v1.16 browserContext.request()

API testing helper associated with this context. Requests made with this API will use context cookies.

Usage

Returns

tracing()Added in: v1.12 browserContext.tracing()

Usage

Returns

Events onBackgroundPage(handler)Added in: v1.11 browserContext.onBackgroundPage(handler)

note

Only works with Chromium browser's persistent context.

Emitted when new background page is created in the context.

context.onBackgroundPage(backgroundPage -> {
System.out.println(backgroundPage.url());
});

Usage

BrowserContext.onBackgroundPage(handler)

Event data

onClose(handler)Added before v1.9 browserContext.onClose(handler)

Emitted when Browser context gets closed. This might happen because of one of the following:

Usage

BrowserContext.onClose(handler)

Event data

onConsoleMessage(handler)Added in: v1.34 browserContext.onConsoleMessage(handler)

Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir.

The arguments passed into console.log and the page are available on the ConsoleMessage event handler argument.

Usage

context.onConsoleMessage(msg -> {
for (int i = 0; i < msg.args().size(); ++i)
System.out.println(i + ": " + msg.args().get(i).jsonValue());
});
page.evaluate("() => console.log('hello', 5, { foo: 'bar' })");

Event data

onDialog(handler)Added in: v1.34 browserContext.onDialog(handler)

Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener must either Dialog.accept() or Dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

Usage

context.onDialog(dialog -> {
dialog.accept();
});

Event data

onPage(handler)Added before v1.9 browserContext.onPage(handler)

The event is emitted when a new Page is created in the BrowserContext. The page may still be loading. The event will also fire for popup pages. See also Page.onPopup(handler) to receive events about popups relevant to a specific page.

The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to this network request, use BrowserContext.route() and BrowserContext.onRequest(handler) respectively instead of similar methods on the Page.

Page newPage = context.waitForPage(() -> {
page.getByText("open new page").click();
});
System.out.println(newPage.evaluate("location.href"));

note

Use Page.waitForLoadState() to wait until the page gets to a particular state (you should not need it in most cases).

Usage

BrowserContext.onPage(handler)

Event data

onRequest(handler)Added in: v1.12 browserContext.onRequest(handler)

Emitted when a request is issued from any pages created through this context. The request object is read-only. To only listen for requests from a particular page, use Page.onRequest(handler).

In order to intercept and mutate requests, see BrowserContext.route() or Page.route().

Usage

BrowserContext.onRequest(handler)

Event data

onRequestFailed(handler)Added in: v1.12 browserContext.onRequestFailed(handler)

Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use Page.onRequestFailed(handler).

Usage

BrowserContext.onRequestFailed(handler)

Event data

onRequestFinished(handler)Added in: v1.12 browserContext.onRequestFinished(handler)

Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished. To listen for successful requests from a particular page, use Page.onRequestFinished(handler).

Usage

BrowserContext.onRequestFinished(handler)

Event data

onResponse(handler)Added in: v1.12 browserContext.onResponse(handler)

Emitted when response status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished. To listen for response events from a particular page, use Page.onResponse(handler).

Usage

BrowserContext.onResponse(handler)

Event data

onWebError(handler)Added in: v1.38 browserContext.onWebError(handler)

Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, use Page.onPageError(handler) instead.

Usage

BrowserContext.onWebError(handler)

Event data


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4