public interface BrowserContext extends AutoCloseable
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 "incognito" browser contexts with Browser.newContext()
method.
"Incognito" 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();
Modifier and Type | Interface and Description |
---|---|
static class |
BrowserContext.ExposeBindingOptions |
static class |
BrowserContext.GrantPermissionsOptions |
static class |
BrowserContext.RouteFromHAROptions |
static class |
BrowserContext.RouteOptions |
static class |
BrowserContext.StorageStateOptions |
static class |
BrowserContext.WaitForPageOptions |
Modifier and Type | Method and Description |
---|---|
void |
addCookies(List<Cookie> cookies)
Adds cookies into this 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.
|
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.
|
Browser |
browser()
Returns the browser instance of the context.
|
void |
clearCookies()
Clears context cookies.
|
void |
clearPermissions()
Clears all permission overrides for the browser context.
|
void |
close()
Closes the browser context.
|
default List<Cookie> |
cookies()
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.
|
List<Cookie> |
cookies(String urls)
If no URLs are specified, this method returns all cookies.
|
default void |
exposeBinding(String name,
BindingCallback callback)
The method adds a function called
name on the window object of every frame in every page in the context. |
void |
exposeBinding(String name,
BindingCallback callback,
BrowserContext.ExposeBindingOptions options)
The method adds a function called
name on the window object of every frame in every page in the context. |
void |
exposeFunction(String name,
FunctionCallback callback)
The method adds a function called
name on the window 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.
|
Page |
newPage()
Creates a new page in the browser context.
|
void |
offClose(Consumer<BrowserContext> handler)
Removes handler that was previously added with
onClose(handler) . |
void |
offPage(Consumer<Page> handler)
Removes handler that was previously added with
onPage(handler) . |
void |
offRequest(Consumer<Request> handler)
Removes handler that was previously added with
onRequest(handler) . |
void |
offRequestFailed(Consumer<Request> handler)
Removes handler that was previously added with
onRequestFailed(handler) . |
void |
offRequestFinished(Consumer<Request> handler)
Removes handler that was previously added with
onRequestFinished(handler) . |
void |
offResponse(Consumer<Response> handler)
Removes handler that was previously added with
onResponse(handler) . |
void |
onClose(Consumer<BrowserContext> handler)
Emitted when Browser context gets closed.
|
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.
|
List<Page> |
pages()
Returns all open pages in the context.
|
APIRequestContext |
request()
API testing helper associated with this 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 |
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(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 |
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 |
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 accepting
timeout 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 and local storage snapshot.
|
String |
storageState(BrowserContext.StorageStateOptions options)
Returns storage state for this browser context, contains current cookies and local storage snapshot.
|
Tracing |
tracing() |
default void |
unroute(Pattern url)
Removes a route created with
BrowserContext.route() . |
void |
unroute(Pattern url,
Consumer<Route> handler)
Removes a route created with
BrowserContext.route() . |
default void |
unroute(Predicate<String> url)
Removes a route created with
BrowserContext.route() . |
void |
unroute(Predicate<String> url,
Consumer<Route> handler)
Removes a route created with
BrowserContext.route() . |
default void |
unroute(String url)
Removes a route created with
BrowserContext.route() . |
void |
unroute(String url,
Consumer<Route> handler)
Removes a route created with
BrowserContext.route() . |
Page |
waitForPage(BrowserContext.WaitForPageOptions options,
Runnable callback)
Performs action and waits for a new
Page to be created in the context. |
default Page |
waitForPage(Runnable callback)
Performs action and waits for a new
Page to be created in the context. |
void onClose(Consumer<BrowserContext> handler)
Browser.close()
method was called.void offClose(Consumer<BrowserContext> handler)
onClose(handler)
.void onPage(Consumer<Page> handler)
Page.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.
Page newPage = context.waitForPage(() -> {
page.locator("a[target=_blank]").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).
void offPage(Consumer<Page> handler)
onPage(handler)
.void onRequest(Consumer<Request> handler)
Page.onRequest()
.
In order to intercept and mutate requests, see BrowserContext.route()
or Page.route()
.
void offRequest(Consumer<Request> handler)
onRequest(handler)
.void onRequestFailed(Consumer<Request> handler)
Page.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 with BrowserContext.onRequestFailed()
.
void offRequestFailed(Consumer<Request> handler)
onRequestFailed(handler)
.void onRequestFinished(Consumer<Request> handler)
request
, response
and requestfinished
. To listen for successful requests from a particular
page, use Page.onRequestFinished()
.void offRequestFinished(Consumer<Request> handler)
onRequestFinished(handler)
.void onResponse(Consumer<Response> handler)
request
, response
and requestfinished
. To listen for response events from a particular page, use Page.onResponse()
.void offResponse(Consumer<Response> handler)
onResponse(handler)
.void addCookies(List<Cookie> cookies)
BrowserContext.cookies()
.
browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));
void addInitScript(String script)
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
.
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()
and Page.addInitScript()
is not defined.
script
- Script to be evaluated in all pages in the browser context.void addInitScript(Path script)
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
.
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()
and Page.addInitScript()
is not defined.
script
- Script to be evaluated in all pages in the browser context.Browser browser()
void clearCookies()
void clearPermissions()
BrowserContext context = browser.newContext();
context.grantPermissions(Arrays.asList("clipboard-read"));
// do stuff ..
context.clearPermissions();
void close()
NOTE: The default browser context cannot be closed.
close
in interface AutoCloseable
default List<Cookie> cookies()
List<Cookie> cookies(String urls)
urls
- Optional list of URLs.List<Cookie> cookies(List<String> urls)
urls
- Optional list of URLs.default void exposeBinding(String name, BindingCallback callback)
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.
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("button").click();
}
}
}
An example of passing an element handle:
context.exposeBinding("clicked", (source, args) -> {
ElementHandle element = (ElementHandle) args[0];
System.out.println(element.textContent());
return null;
}, new BrowserContext.ExposeBindingOptions().setHandle(true));
page.setContent("" +
"<script>\n" +
" document.addEventListener('click', event => window.clicked(event.target));\n" +
"</script>\n" +
"<div>Click me</div>\n" +
"<div>Or click me</div>\n");
name
- Name of the function on the window object.callback
- Callback function that will be called in the Playwright's context.void exposeBinding(String name, BindingCallback callback, BrowserContext.ExposeBindingOptions options)
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.
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("button").click();
}
}
}
An example of passing an element handle:
context.exposeBinding("clicked", (source, args) -> {
ElementHandle element = (ElementHandle) args[0];
System.out.println(element.textContent());
return null;
}, new BrowserContext.ExposeBindingOptions().setHandle(true));
page.setContent("" +
"<script>\n" +
" document.addEventListener('click', event => window.clicked(event.target));\n" +
"</script>\n" +
"<div>Click me</div>\n" +
"<div>Or click me</div>\n");
name
- Name of the function on the window object.callback
- Callback function that will be called in the Playwright's context.void exposeFunction(String name, FunctionCallback callback)
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.
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));
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("button").click();
}
}
}
name
- Name of the function on the window object.callback
- Callback function that will be called in the Playwright's context.default void grantPermissions(List<String> permissions)
permissions
- A permission or an array of permissions to grant. Permissions can be one of the following values:
"geolocation"
"midi"
"midi-sysex"
(system-exclusive midi)"notifications"
"camera"
"microphone"
"background-sync"
"ambient-light-sensor"
"accelerometer"
"gyroscope"
"magnetometer"
"accessibility-events"
"clipboard-read"
"clipboard-write"
"payment-handler"
void grantPermissions(List<String> permissions, BrowserContext.GrantPermissionsOptions options)
permissions
- A permission or an array of permissions to grant. Permissions can be one of the following values:
"geolocation"
"midi"
"midi-sysex"
(system-exclusive midi)"notifications"
"camera"
"microphone"
"background-sync"
"ambient-light-sensor"
"accelerometer"
"gyroscope"
"magnetometer"
"accessibility-events"
"clipboard-read"
"clipboard-write"
"payment-handler"
Page newPage()
APIRequestContext request()
default void route(String url, Consumer<Route> handler)
NOTE: BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when
using request interception by setting Browser.newContext.serviceWorkers
to "block"
.
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.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL
via the context
options was provided and the passed URL is a path, it gets merged via the new URL()
constructor.handler
- handler function to route the request.void route(String url, Consumer<Route> handler, BrowserContext.RouteOptions options)
NOTE: BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when
using request interception by setting Browser.newContext.serviceWorkers
to "block"
.
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.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL
via the context
options was provided and the passed URL is a path, it gets merged via the new URL()
constructor.handler
- handler function to route the request.default void route(Pattern url, Consumer<Route> handler)
NOTE: BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when
using request interception by setting Browser.newContext.serviceWorkers
to "block"
.
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.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL
via the context
options was provided and the passed URL is a path, it gets merged via the new URL()
constructor.handler
- handler function to route the request.void route(Pattern url, Consumer<Route> handler, BrowserContext.RouteOptions options)
NOTE: BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when
using request interception by setting Browser.newContext.serviceWorkers
to "block"
.
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.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL
via the context
options was provided and the passed URL is a path, it gets merged via the new URL()
constructor.handler
- handler function to route the request.default void route(Predicate<String> url, Consumer<Route> handler)
NOTE: BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when
using request interception by setting Browser.newContext.serviceWorkers
to "block"
.
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.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL
via the context
options was provided and the passed URL is a path, it gets merged via the new URL()
constructor.handler
- handler function to route the request.void route(Predicate<String> url, Consumer<Route> handler, BrowserContext.RouteOptions options)
NOTE: BrowserContext.route()
will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when
using request interception by setting Browser.newContext.serviceWorkers
to "block"
.
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.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL
via the context
options was provided and the passed URL is a path, it gets merged via the new URL()
constructor.handler
- handler function to route the request.default void routeFromHAR(Path 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 Browser.newContext.serviceWorkers
to "block"
.
har
- Path to a HAR file with prerecorded network data. If path
is a relative path, then it is resolved relative to the current working directory.void routeFromHAR(Path har, BrowserContext.RouteFromHAROptions options)
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 Browser.newContext.serviceWorkers
to "block"
.
har
- Path to a HAR file with prerecorded network data. If path
is a relative path, then it is resolved relative to the current working directory.void setDefaultNavigationTimeout(double timeout)
Page.goBack()
Page.goForward()
Page.navigate()
Page.reload()
Page.setContent()
Page.waitForNavigation()
NOTE: Page.setDefaultNavigationTimeout()
and Page.setDefaultTimeout()
take priority over BrowserContext.setDefaultNavigationTimeout()
.
timeout
- Maximum navigation time in millisecondsvoid setDefaultTimeout(double timeout)
timeout
option.
NOTE: Page.setDefaultNavigationTimeout()
, Page.setDefaultTimeout()
and BrowserContext.setDefaultNavigationTimeout()
take priority over BrowserContext.setDefaultTimeout()
.
timeout
- Maximum time in millisecondsvoid setExtraHTTPHeaders(Map<String,String> headers)
Page.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.
headers
- An object containing additional HTTP headers to be sent with every request. All header values must be strings.void setGeolocation(Geolocation geolocation)
null
or undefined
emulates position unavailable.
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.
void setOffline(boolean offline)
offline
- Whether to emulate network being offline for the browser context.default String storageState()
String storageState(BrowserContext.StorageStateOptions options)
Tracing tracing()
default void unroute(String url)
BrowserContext.route()
. When handler
is not specified,
removes all routes for the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route()
.void unroute(String url, Consumer<Route> handler)
BrowserContext.route()
. When handler
is not specified,
removes all routes for the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route()
.handler
- Optional handler function used to register a routing with BrowserContext.route()
.default void unroute(Pattern url)
BrowserContext.route()
. When handler
is not specified,
removes all routes for the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route()
.void unroute(Pattern url, Consumer<Route> handler)
BrowserContext.route()
. When handler
is not specified,
removes all routes for the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route()
.handler
- Optional handler function used to register a routing with BrowserContext.route()
.default void unroute(Predicate<String> url)
BrowserContext.route()
. When handler
is not specified,
removes all routes for the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route()
.void unroute(Predicate<String> url, Consumer<Route> handler)
BrowserContext.route()
. When handler
is not specified,
removes all routes for the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route()
.handler
- Optional handler function used to register a routing with BrowserContext.route()
.default Page waitForPage(Runnable callback)
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.callback
- Callback that performs the action triggering the event.Page waitForPage(BrowserContext.WaitForPageOptions options, Runnable callback)
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.callback
- Callback that performs the action triggering the event.Copyright © 2022. All rights reserved.