Interface BrowserContext
-
- All Superinterfaces:
AutoCloseable
public interface BrowserContext extends AutoCloseable
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.// Create a new incognito browser context BrowserContext context = browser.newContext(); // Create a new page inside context. Page page = context.newPage(); page.navigate("https://example.com"); // Dispose context once it is no longer needed. context.close();
-
-
Nested Class Summary
Nested Classes Modifier and Type Interface Description static class
BrowserContext.ClearCookiesOptions
static class
BrowserContext.CloseOptions
static class
BrowserContext.ExposeBindingOptions
static class
BrowserContext.GrantPermissionsOptions
static class
BrowserContext.RouteFromHAROptions
static class
BrowserContext.RouteOptions
static class
BrowserContext.StorageStateOptions
static class
BrowserContext.WaitForConditionOptions
static class
BrowserContext.WaitForConsoleMessageOptions
static class
BrowserContext.WaitForPageOptions
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Modifier and Type Method Description void
addCookies(List<Cookie> cookies)
Adds cookies into this browser context.void
addInitScript(String script)
Adds a script which would be evaluated in one of the following scenarios: Whenever a page is created in the browser context or is navigated. Whenever a child frame is attached or navigated in any page in the browser context.void
addInitScript(Path script)
Adds a script which would be evaluated in one of the following scenarios: Whenever a page is created in the browser context or is navigated. Whenever a child frame is attached or navigated in any page in the browser context.List<Page>
backgroundPages()
NOTE: Background pages are only supported on Chromium-based browsers.Browser
browser()
Returns the browser instance of the context.default void
clearCookies()
Removes cookies from context.void
clearCookies(BrowserContext.ClearCookiesOptions options)
Removes cookies from context.void
clearPermissions()
Clears all permission overrides for the browser context.Clock
clock()
Playwright has ability to mock clock and passage of time.default void
close()
Closes the browser context.void
close(BrowserContext.CloseOptions options)
Closes the browser context.default List<Cookie>
cookies()
If no URLs are specified, this method returns all cookies.List<Cookie>
cookies(String urls)
If no URLs are specified, this method returns all cookies.List<Cookie>
cookies(List<String> urls)
If no URLs are specified, this method returns all cookies.default void
exposeBinding(String name, BindingCallback callback)
The method adds a function calledname
on thewindow
object of every frame in every page in the context.void
exposeBinding(String name, BindingCallback callback, BrowserContext.ExposeBindingOptions options)
The method adds a function calledname
on thewindow
object of every frame in every page in the context.void
exposeFunction(String name, FunctionCallback callback)
The method adds a function calledname
on thewindow
object of every frame in every page in the context.default void
grantPermissions(List<String> permissions)
Grants specified permissions to the browser context.void
grantPermissions(List<String> permissions, BrowserContext.GrantPermissionsOptions options)
Grants specified permissions to the browser context.CDPSession
newCDPSession(Frame page)
NOTE: CDP sessions are only supported on Chromium-based browsers.CDPSession
newCDPSession(Page page)
NOTE: CDP sessions are only supported on Chromium-based browsers.Page
newPage()
Creates a new page in the browser context.void
offBackgroundPage(Consumer<Page> handler)
Removes handler that was previously added withonBackgroundPage(handler)
.void
offClose(Consumer<BrowserContext> handler)
Removes handler that was previously added withonClose(handler)
.void
offConsoleMessage(Consumer<ConsoleMessage> handler)
Removes handler that was previously added withonConsoleMessage(handler)
.void
offDialog(Consumer<Dialog> handler)
Removes handler that was previously added withonDialog(handler)
.void
offPage(Consumer<Page> handler)
Removes handler that was previously added withonPage(handler)
.void
offRequest(Consumer<Request> handler)
Removes handler that was previously added withonRequest(handler)
.void
offRequestFailed(Consumer<Request> handler)
Removes handler that was previously added withonRequestFailed(handler)
.void
offRequestFinished(Consumer<Request> handler)
Removes handler that was previously added withonRequestFinished(handler)
.void
offResponse(Consumer<Response> handler)
Removes handler that was previously added withonResponse(handler)
.void
offWebError(Consumer<WebError> handler)
Removes handler that was previously added withonWebError(handler)
.void
onBackgroundPage(Consumer<Page> handler)
NOTE: Only works with Chromium browser's persistent context.void
onClose(Consumer<BrowserContext> handler)
Emitted when Browser context gets closed.void
onConsoleMessage(Consumer<ConsoleMessage> handler)
Emitted when JavaScript within the page calls one of console API methods, e.g.void
onDialog(Consumer<Dialog> handler)
Emitted when a JavaScript dialog appears, such asalert
,prompt
,confirm
orbeforeunload
.void
onPage(Consumer<Page> handler)
The event is emitted when a new Page is created in the BrowserContext.void
onRequest(Consumer<Request> handler)
Emitted when a request is issued from any pages created through this context.void
onRequestFailed(Consumer<Request> handler)
Emitted when a request fails, for example by timing out.void
onRequestFinished(Consumer<Request> handler)
Emitted when a request finishes successfully after downloading the response body.void
onResponse(Consumer<Response> handler)
Emitted when [response] status and headers are received for a request.void
onWebError(Consumer<WebError> handler)
Emitted when exception is unhandled in any of the pages in this context.List<Page>
pages()
Returns all open pages in the context.APIRequestContext
request()
API testing helper associated with this context.default void
route(String url, Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by any page in the browser context.void
route(String url, Consumer<Route> handler, BrowserContext.RouteOptions options)
Routing provides the capability to modify network requests that are made by any page in the browser context.default void
route(Predicate<String> url, Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by any page in the browser context.void
route(Predicate<String> url, Consumer<Route> handler, BrowserContext.RouteOptions options)
Routing provides the capability to modify network requests that are made by any page in the browser context.default void
route(Pattern url, Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by any page in the browser context.void
route(Pattern url, Consumer<Route> handler, BrowserContext.RouteOptions options)
Routing provides the capability to modify network requests that are made by any page in the browser context.default void
routeFromHAR(Path har)
If specified the network requests that are made in the context will be served from the HAR file.void
routeFromHAR(Path har, BrowserContext.RouteFromHAROptions options)
If specified the network requests that are made in the context will be served from the HAR file.void
routeWebSocket(String url, Consumer<WebSocketRoute> handler)
This method allows to modify websocket connections that are made by any page in the browser context.void
routeWebSocket(Predicate<String> url, Consumer<WebSocketRoute> handler)
This method allows to modify websocket connections that are made by any page in the browser context.void
routeWebSocket(Pattern url, Consumer<WebSocketRoute> handler)
This method allows to modify websocket connections that are made by any page in the browser context.void
setDefaultNavigationTimeout(double timeout)
This setting will change the default maximum navigation time for the following methods and related shortcuts:Page.goBack()
Page.goForward()
Page.navigate()
Page.reload()
Page.setContent()
Page.waitForNavigation()
void
setDefaultTimeout(double timeout)
This setting will change the default maximum time for all the methods acceptingtimeout
option.void
setExtraHTTPHeaders(Map<String,String> headers)
The extra HTTP headers will be sent with every request initiated by any page in the context.void
setGeolocation(Geolocation geolocation)
Sets the context's geolocation.void
setOffline(boolean offline)
default String
storageState()
Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.String
storageState(BrowserContext.StorageStateOptions options)
Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.Tracing
tracing()
default void
unroute(String url)
Removes a route created withBrowserContext.route()
.void
unroute(String url, Consumer<Route> handler)
Removes a route created withBrowserContext.route()
.default void
unroute(Predicate<String> url)
Removes a route created withBrowserContext.route()
.void
unroute(Predicate<String> url, Consumer<Route> handler)
Removes a route created withBrowserContext.route()
.default void
unroute(Pattern url)
Removes a route created withBrowserContext.route()
.void
unroute(Pattern url, Consumer<Route> handler)
Removes a route created withBrowserContext.route()
.void
unrouteAll()
Removes all routes created withBrowserContext.route()
andBrowserContext.routeFromHAR()
.default void
waitForCondition(BooleanSupplier condition)
The method will block until the condition returns true.void
waitForCondition(BooleanSupplier condition, BrowserContext.WaitForConditionOptions options)
The method will block until the condition returns true.ConsoleMessage
waitForConsoleMessage(BrowserContext.WaitForConsoleMessageOptions options, Runnable callback)
Performs action and waits for aConsoleMessage
to be logged by in the pages in the context.default ConsoleMessage
waitForConsoleMessage(Runnable callback)
Performs action and waits for aConsoleMessage
to be logged by in the pages in the context.Page
waitForPage(BrowserContext.WaitForPageOptions options, Runnable callback)
Performs action and waits for a newPage
to be created in the context.default Page
waitForPage(Runnable callback)
Performs action and waits for a newPage
to be created in the context.
-
-
-
Method Detail
-
onBackgroundPage
void onBackgroundPage(Consumer<Page> 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()); });
-
offBackgroundPage
void offBackgroundPage(Consumer<Page> handler)
Removes handler that was previously added withonBackgroundPage(handler)
.
-
onClose
void onClose(Consumer<BrowserContext> handler)
Emitted when Browser context gets closed. This might happen because of one of the following:- Browser context is closed.
- Browser application is closed or crashed.
- The
Browser.close()
method was called.
-
offClose
void offClose(Consumer<BrowserContext> handler)
Removes handler that was previously added withonClose(handler)
.
-
onConsoleMessage
void onConsoleMessage(Consumer<ConsoleMessage> handler)
Emitted when JavaScript within the page calls one of console API methods, e.g.console.log
orconsole.dir
.The arguments passed into
console.log
and the page are available on theConsoleMessage
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' })");
-
offConsoleMessage
void offConsoleMessage(Consumer<ConsoleMessage> handler)
Removes handler that was previously added withonConsoleMessage(handler)
.
-
onDialog
void onDialog(Consumer<Dialog> handler)
Emitted when a JavaScript dialog appears, such asalert
,prompt
,confirm
orbeforeunload
. Listener **must** eitherDialog.accept()
orDialog.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(); });
NOTE: When no
Page.onDialog()
orBrowserContext.onDialog()
listeners are present, all dialogs are automatically dismissed.
-
offDialog
void offDialog(Consumer<Dialog> handler)
Removes handler that was previously added withonDialog(handler)
.
-
onPage
void onPage(Consumer<Page> 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 alsoPage.onPopup()
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, useBrowserContext.route()
andBrowserContext.onRequest()
respectively instead of similar methods on thePage
.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).
-
offPage
void offPage(Consumer<Page> handler)
Removes handler that was previously added withonPage(handler)
.
-
onWebError
void onWebError(Consumer<WebError> handler)
Emitted when exception is unhandled in any of the pages in this context. To listen for errors from a particular page, usePage.onPageError()
instead.
-
offWebError
void offWebError(Consumer<WebError> handler)
Removes handler that was previously added withonWebError(handler)
.
-
onRequest
void onRequest(Consumer<Request> 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, usePage.onRequest()
.In order to intercept and mutate requests, see
BrowserContext.route()
orPage.route()
.
-
offRequest
void offRequest(Consumer<Request> handler)
Removes handler that was previously added withonRequest(handler)
.
-
onRequestFailed
void onRequestFailed(Consumer<Request> handler)
Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, usePage.onRequestFailed()
.NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with
BrowserContext.onRequestFinished()
event and not withBrowserContext.onRequestFailed()
.
-
offRequestFailed
void offRequestFailed(Consumer<Request> handler)
Removes handler that was previously added withonRequestFailed(handler)
.
-
onRequestFinished
void onRequestFinished(Consumer<Request> handler)
Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events isrequest
,response
andrequestfinished
. To listen for successful requests from a particular page, usePage.onRequestFinished()
.
-
offRequestFinished
void offRequestFinished(Consumer<Request> handler)
Removes handler that was previously added withonRequestFinished(handler)
.
-
onResponse
void onResponse(Consumer<Response> handler)
Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events isrequest
,response
andrequestfinished
. To listen for response events from a particular page, usePage.onResponse()
.
-
offResponse
void offResponse(Consumer<Response> handler)
Removes handler that was previously added withonResponse(handler)
.
-
clock
Clock clock()
Playwright has ability to mock clock and passage of time.- Since:
- v1.45
-
addCookies
void addCookies(List<Cookie> cookies)
Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained viaBrowserContext.cookies()
.Usage
browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));
- Since:
- v1.8
-
addInitScript
void addInitScript(String script)
Adds a script which would be evaluated in one of the following scenarios:- Whenever a page is created in the browser context or is navigated.
- Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.
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:// In your playwright script, assuming the preload.js file is in same directory. browserContext.addInitScript(Paths.get("preload.js"));
NOTE: The order of evaluation of multiple scripts installed via
BrowserContext.addInitScript()
andPage.addInitScript()
is not defined.- Parameters:
script
- Script to be evaluated in all pages in the browser context.- Since:
- v1.8
-
addInitScript
void addInitScript(Path script)
Adds a script which would be evaluated in one of the following scenarios:- Whenever a page is created in the browser context or is navigated.
- Whenever a child frame is attached or navigated in any page in the browser context. In this case, the script is evaluated in the context of the newly attached frame.
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:// In your playwright script, assuming the preload.js file is in same directory. browserContext.addInitScript(Paths.get("preload.js"));
NOTE: The order of evaluation of multiple scripts installed via
BrowserContext.addInitScript()
andPage.addInitScript()
is not defined.- Parameters:
script
- Script to be evaluated in all pages in the browser context.- Since:
- v1.8
-
backgroundPages
List<Page> backgroundPages()
NOTE: Background pages are only supported on Chromium-based browsers.All existing background pages in the context.
- Since:
- v1.11
-
browser
Browser browser()
Returns the browser instance of the context. If it was launched as a persistent context null gets returned.- Since:
- v1.8
-
clearCookies
default void 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"));
- Since:
- v1.8
-
clearCookies
void clearCookies(BrowserContext.ClearCookiesOptions options)
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"));
- Since:
- v1.8
-
clearPermissions
void clearPermissions()
Clears all permission overrides for the browser context.Usage
BrowserContext context = browser.newContext(); context.grantPermissions(Arrays.asList("clipboard-read")); // do stuff .. context.clearPermissions();
- Since:
- v1.8
-
close
default void 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.
- Specified by:
close
in interfaceAutoCloseable
- Since:
- v1.8
-
close
void close(BrowserContext.CloseOptions options)
Closes the browser context. All the pages that belong to the browser context will be closed.NOTE: The default browser context cannot be closed.
- Since:
- v1.8
-
cookies
default List<Cookie> cookies()
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.- Since:
- v1.8
-
cookies
List<Cookie> cookies(String urls)
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.- Parameters:
urls
- Optional list of URLs.- Since:
- v1.8
-
cookies
List<Cookie> cookies(List<String> urls)
If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.- Parameters:
urls
- Optional list of URLs.- Since:
- v1.8
-
exposeBinding
default void exposeBinding(String name, BindingCallback callback)
The method adds a function calledname
on thewindow
object of every frame in every page in the context. When called, the function executescallback
and returns a Promise which resolves to the return value ofcallback
. If thecallback
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(); } } }
- Parameters:
name
- Name of the function on the window object.callback
- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
exposeBinding
void exposeBinding(String name, BindingCallback callback, BrowserContext.ExposeBindingOptions options)
The method adds a function calledname
on thewindow
object of every frame in every page in the context. When called, the function executescallback
and returns a Promise which resolves to the return value ofcallback
. If thecallback
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(); } } }
- Parameters:
name
- Name of the function on the window object.callback
- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
exposeFunction
void exposeFunction(String name, FunctionCallback callback)
The method adds a function calledname
on thewindow
object of every frame in every page in the context. When called, the function executescallback
and returns a Promise which resolves to the return value ofcallback
.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(); } } }
- Parameters:
name
- Name of the function on the window object.callback
- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
grantPermissions
default void grantPermissions(List<String> permissions)
Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.- Parameters:
permissions
- A list of permissions to grant.NOTE: Supported permissions differ between browsers, and even between different versions of the same browser. Any permission may stop working after an update.
Here are some permissions that may be supported by some browsers:
-
"accelerometer"
-
"ambient-light-sensor"
-
"background-sync"
-
"camera"
-
"clipboard-read"
-
"clipboard-write"
-
"geolocation"
-
"gyroscope"
-
"magnetometer"
-
"microphone"
-
"midi-sysex"
(system-exclusive midi) -
"midi"
-
"notifications"
-
"payment-handler"
-
"storage-access"
-
- Since:
- v1.8
-
grantPermissions
void grantPermissions(List<String> permissions, BrowserContext.GrantPermissionsOptions options)
Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.- Parameters:
permissions
- A list of permissions to grant.NOTE: Supported permissions differ between browsers, and even between different versions of the same browser. Any permission may stop working after an update.
Here are some permissions that may be supported by some browsers:
-
"accelerometer"
-
"ambient-light-sensor"
-
"background-sync"
-
"camera"
-
"clipboard-read"
-
"clipboard-write"
-
"geolocation"
-
"gyroscope"
-
"magnetometer"
-
"microphone"
-
"midi-sysex"
(system-exclusive midi) -
"midi"
-
"notifications"
-
"payment-handler"
-
"storage-access"
-
- Since:
- v1.8
-
newCDPSession
CDPSession newCDPSession(Page page)
NOTE: CDP sessions are only supported on Chromium-based browsers.Returns the newly created session.
- Parameters:
page
- Target to create new session for. For backwards-compatibility, this parameter is namedpage
, but it can be aPage
orFrame
type.- Since:
- v1.11
-
newCDPSession
CDPSession newCDPSession(Frame page)
NOTE: CDP sessions are only supported on Chromium-based browsers.Returns the newly created session.
- Parameters:
page
- Target to create new session for. For backwards-compatibility, this parameter is namedpage
, but it can be aPage
orFrame
type.- Since:
- v1.11
-
newPage
Page newPage()
Creates a new page in the browser context.- Since:
- v1.8
-
request
APIRequestContext request()
API testing helper associated with this context. Requests made with this API will use context cookies.- Since:
- v1.16
-
route
default void route(String url, Consumer<Route> handler)
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.NOTE:
BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingserviceWorkers
to"block"
.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.
- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
- handler function to route the request.- Since:
- v1.8
-
route
void route(String url, Consumer<Route> handler, BrowserContext.RouteOptions options)
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.NOTE:
BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingserviceWorkers
to"block"
.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.
- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
- handler function to route the request.- Since:
- v1.8
-
route
default void route(Pattern url, Consumer<Route> handler)
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.NOTE:
BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingserviceWorkers
to"block"
.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.
- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
- handler function to route the request.- Since:
- v1.8
-
route
void route(Pattern url, Consumer<Route> handler, BrowserContext.RouteOptions options)
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.NOTE:
BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingserviceWorkers
to"block"
.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.
- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
- handler function to route the request.- Since:
- v1.8
-
route
default void route(Predicate<String> url, Consumer<Route> handler)
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.NOTE:
BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingserviceWorkers
to"block"
.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.
- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
- handler function to route the request.- Since:
- v1.8
-
route
void route(Predicate<String> url, Consumer<Route> handler, BrowserContext.RouteOptions options)
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.NOTE:
BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingserviceWorkers
to"block"
.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.
- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURL
via the context options was provided and the passed URL is a path, it gets merged via thenew URL()
constructor.handler
- handler function to route the request.- Since:
- v1.8
-
routeFromHAR
default void routeFromHAR(Path har)
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
serviceWorkers
to"block"
.- Parameters:
har
- Path to a HAR file with prerecorded network data. Ifpath
is a relative path, then it is resolved relative to the current working directory.- Since:
- v1.23
-
routeFromHAR
void routeFromHAR(Path har, BrowserContext.RouteFromHAROptions options)
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
serviceWorkers
to"block"
.- Parameters:
har
- Path to a HAR file with prerecorded network data. Ifpath
is a relative path, then it is resolved relative to the current working directory.- Since:
- v1.23
-
routeWebSocket
void routeWebSocket(String url, Consumer<WebSocketRoute> handler)
This method allows to modify websocket connections that are made by any page in the browser context.Note that only
WebSocket
s 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(); });
- Parameters:
url
- Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to thebaseURL
context option.handler
- Handler function to route the WebSocket.- Since:
- v1.48
-
routeWebSocket
void routeWebSocket(Pattern url, Consumer<WebSocketRoute> handler)
This method allows to modify websocket connections that are made by any page in the browser context.Note that only
WebSocket
s 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(); });
- Parameters:
url
- Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to thebaseURL
context option.handler
- Handler function to route the WebSocket.- Since:
- v1.48
-
routeWebSocket
void routeWebSocket(Predicate<String> url, Consumer<WebSocketRoute> handler)
This method allows to modify websocket connections that are made by any page in the browser context.Note that only
WebSocket
s 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(); });
- Parameters:
url
- Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to thebaseURL
context option.handler
- Handler function to route the WebSocket.- Since:
- v1.48
-
setDefaultNavigationTimeout
void setDefaultNavigationTimeout(double timeout)
This setting will change the default maximum navigation time for the following methods and related shortcuts:-
Page.goBack()
-
Page.goForward()
-
Page.navigate()
-
Page.reload()
-
Page.setContent()
-
Page.waitForNavigation()
NOTE:
Page.setDefaultNavigationTimeout()
andPage.setDefaultTimeout()
take priority overBrowserContext.setDefaultNavigationTimeout()
.- Parameters:
timeout
- Maximum navigation time in milliseconds- Since:
- v1.8
-
-
setDefaultTimeout
void setDefaultTimeout(double timeout)
This setting will change the default maximum time for all the methods acceptingtimeout
option.NOTE:
Page.setDefaultNavigationTimeout()
,Page.setDefaultTimeout()
andBrowserContext.setDefaultNavigationTimeout()
take priority overBrowserContext.setDefaultTimeout()
.- Parameters:
timeout
- Maximum time in milliseconds. Pass0
to disable timeout.- Since:
- v1.8
-
setExtraHTTPHeaders
void setExtraHTTPHeaders(Map<String,String> headers)
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 withPage.setExtraHTTPHeaders()
. If page overrides a particular header, page-specific header value will be used instead of the browser context header value.NOTE:
BrowserContext.setExtraHTTPHeaders()
does not guarantee the order of headers in the outgoing requests.- Parameters:
headers
- An object containing additional HTTP headers to be sent with every request. All header values must be strings.- Since:
- v1.8
-
setGeolocation
void setGeolocation(Geolocation geolocation)
Sets the context's geolocation. Passingnull
orundefined
emulates position unavailable.Usage
browserContext.setGeolocation(new Geolocation(59.95, 30.31667));
NOTE: Consider using
BrowserContext.grantPermissions()
to grant permissions for the browser context pages to read its geolocation.- Since:
- v1.8
-
setOffline
void setOffline(boolean offline)
- Parameters:
offline
- Whether to emulate network being offline for the browser context.- Since:
- v1.8
-
storageState
default String storageState()
Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.- Since:
- v1.8
-
storageState
String storageState(BrowserContext.StorageStateOptions options)
Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.- Since:
- v1.8
-
tracing
Tracing tracing()
- Since:
- v1.12
-
unrouteAll
void unrouteAll()
Removes all routes created withBrowserContext.route()
andBrowserContext.routeFromHAR()
.- Since:
- v1.41
-
unroute
default void unroute(String url)
Removes a route created withBrowserContext.route()
. Whenhandler
is not specified, removes all routes for theurl
.- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing withBrowserContext.route()
.- Since:
- v1.8
-
unroute
void unroute(String url, Consumer<Route> handler)
Removes a route created withBrowserContext.route()
. Whenhandler
is not specified, removes all routes for theurl
.- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing withBrowserContext.route()
.handler
- Optional handler function used to register a routing withBrowserContext.route()
.- Since:
- v1.8
-
unroute
default void unroute(Pattern url)
Removes a route created withBrowserContext.route()
. Whenhandler
is not specified, removes all routes for theurl
.- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing withBrowserContext.route()
.- Since:
- v1.8
-
unroute
void unroute(Pattern url, Consumer<Route> handler)
Removes a route created withBrowserContext.route()
. Whenhandler
is not specified, removes all routes for theurl
.- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing withBrowserContext.route()
.handler
- Optional handler function used to register a routing withBrowserContext.route()
.- Since:
- v1.8
-
unroute
default void unroute(Predicate<String> url)
Removes a route created withBrowserContext.route()
. Whenhandler
is not specified, removes all routes for theurl
.- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing withBrowserContext.route()
.- Since:
- v1.8
-
unroute
void unroute(Predicate<String> url, Consumer<Route> handler)
Removes a route created withBrowserContext.route()
. Whenhandler
is not specified, removes all routes for theurl
.- Parameters:
url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing withBrowserContext.route()
.handler
- Optional handler function used to register a routing withBrowserContext.route()
.- Since:
- v1.8
-
waitForCondition
default void waitForCondition(BooleanSupplier condition)
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);
- Parameters:
condition
- Condition to wait for.- Since:
- v1.32
-
waitForCondition
void waitForCondition(BooleanSupplier condition, BrowserContext.WaitForConditionOptions options)
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);
- Parameters:
condition
- Condition to wait for.- Since:
- v1.32
-
waitForConsoleMessage
default ConsoleMessage waitForConsoleMessage(Runnable callback)
Performs action and waits for aConsoleMessage
to be logged by in the pages in the context. If predicate is provided, it passesConsoleMessage
value into thepredicate
function and waits forpredicate(message)
to return a truthy value. Will throw an error if the page is closed before theBrowserContext.onConsoleMessage()
event is fired.- Parameters:
callback
- Callback that performs the action triggering the event.- Since:
- v1.34
-
waitForConsoleMessage
ConsoleMessage waitForConsoleMessage(BrowserContext.WaitForConsoleMessageOptions options, Runnable callback)
Performs action and waits for aConsoleMessage
to be logged by in the pages in the context. If predicate is provided, it passesConsoleMessage
value into thepredicate
function and waits forpredicate(message)
to return a truthy value. Will throw an error if the page is closed before theBrowserContext.onConsoleMessage()
event is fired.- Parameters:
callback
- Callback that performs the action triggering the event.- Since:
- v1.34
-
waitForPage
default Page waitForPage(Runnable callback)
Performs action and waits for a newPage
to be created in the context. If predicate is provided, it passesPage
value into thepredicate
function and waits forpredicate(event)
to return a truthy value. Will throw an error if the context closes before newPage
is created.- Parameters:
callback
- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForPage
Page waitForPage(BrowserContext.WaitForPageOptions options, Runnable callback)
Performs action and waits for a newPage
to be created in the context. If predicate is provided, it passesPage
value into thepredicate
function and waits forpredicate(event)
to return a truthy value. Will throw an error if the context closes before newPage
is created.- Parameters:
callback
- Callback that performs the action triggering the event.- Since:
- v1.9
-
-