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.
// 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();
方法 (Methods)
addCookies
Added before v1.9Adds cookies into this browser context. All pages within this context will have these cookies installed. Cookies can be obtained via BrowserContext.cookies().
使用方式
browserContext.addCookies(Arrays.asList(cookieObject1, cookieObject2));
參數
cookies
List<Cookie
>#-
setName
String -
setValue
String -
setUrl
String (optional)Either url or domain / path are required. Optional.
-
setDomain
String (optional)For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com". Either url or domain / path are required. Optional.
-
setPath
String (optional)Either url or domain / path are required Optional.
-
setExpires
double (optional)Unix time in seconds. Optional.
-
setHttpOnly
boolean (optional)Optional.
-
setSecure
boolean (optional)Optional.
-
setSameSite
enum SameSiteAttribute { STRICT, LAX, NONE }
(optional)Optional.
-
setPartitionKey
String (optional)For partitioned third-party cookies (aka CHIPS), the partition key. Optional.
-
傳回值
addInitScript
Added before v1.9Adds 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
.
使用方式
An example of overriding Math.random
before the page loads:
// preload.js
Math.random = () => 42;
// In your playwright script, assuming the preload.js file is in same directory.
browserContext.addInitScript(Paths.get("preload.js"));
The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and Page.addInitScript() is not defined.
參數
傳回值
backgroundPages
Added in: v1.11Background pages are only supported on Chromium-based browsers.
All existing background pages in the context.
使用方式
BrowserContext.backgroundPages();
傳回值
browser
Added before v1.9Gets the browser instance that owns the context. Returns null
if the context is created outside of normal browser, e.g. Android or Electron.
使用方式
BrowserContext.browser();
傳回值
clearCookies
Added before v1.9Removes cookies from context. Accepts optional filter.
使用方式
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"));
參數
options
BrowserContext.ClearCookiesOptions
(optional)
傳回值
clearPermissions
Added before v1.9Clears all permission overrides for the browser context.
使用方式
BrowserContext context = browser.newContext();
context.grantPermissions(Arrays.asList("clipboard-read"));
// do stuff ..
context.clearPermissions();
傳回值
close
Added before v1.9Closes the browser context. All the pages that belong to the browser context will be closed.
The default browser context cannot be closed.
使用方式
BrowserContext.close();
BrowserContext.close(options);
參數
options
BrowserContext.CloseOptions
(optional)
傳回值
cookies
Added before v1.9If no URLs are specified, this method returns all cookies. If URLs are specified, only cookies that affect those URLs are returned.
使用方式
BrowserContext.cookies();
BrowserContext.cookies(urls);
參數
傳回值
exposeBinding
Added before v1.9The 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.
使用方式
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();
}
}
}
參數
-
Name of the function on the window object.
-
callback
BindingCallback
#Callback function that will be called in the Playwright's context.
-
options
BrowserContext.ExposeBindingOptions
(optional)
傳回值
exposeFunction
Added before v1.9The 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.
使用方式
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();
}
}
}
參數
-
Name of the function on the window object.
-
callback
FunctionCallback
#Callback function that will be called in the Playwright's context.
傳回值
grantPermissions
Added before v1.9Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if specified.
使用方式
BrowserContext.grantPermissions(permissions);
BrowserContext.grantPermissions(permissions, options);
參數
-
A list of permissions to grant.
dangerSupported 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'
'local-fonts'
-
options
BrowserContext.GrantPermissionsOptions
(optional)-
The origin to grant permissions to, e.g. "https://example.com".
-
傳回值
newCDPSession
Added in: v1.11CDP sessions are only supported on Chromium-based browsers.
Returns the newly created session.
使用方式
BrowserContext.newCDPSession(page);
參數
-
Target to create new session for. For backwards-compatibility, this parameter is named
page
, but it can be aPage
orFrame
type.
傳回值
newPage
Added before v1.9Creates a new page in the browser context.
使用方式
BrowserContext.newPage();
傳回值
pages
Added before v1.9Returns all open pages in the context.
使用方式
BrowserContext.pages();
傳回值
route
Added before v1.9Routing 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.
BrowserContext.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by setting setServiceWorkers 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().
Enabling routing disables http cache.
參數
-
url
String | Pattern | Predicate<String>#A glob pattern, regex pattern, or predicate that receives a [URL] to match during routing. If setBaseURL is set in the context options and the provided URL is a string that does not start with
*
, it is resolved using thenew URL()
constructor. -
handler function to route the request.
-
options
BrowserContext.RouteOptions
(optional)
傳回值
routeFromHAR
Added in: v1.23If 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'
.
使用方式
BrowserContext.routeFromHAR(har);
BrowserContext.routeFromHAR(har, options);
參數
-
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. -
options
BrowserContext.RouteFromHAROptions
(optional)-
setNotFound
enum HarNotFound { ABORT, FALLBACK }
(optional)#- If set to 'abort' any request not found in the HAR file will be aborted.
- If set to 'fallback' falls through to the next route handler in the handler chain.
Defaults to abort.
-
If specified, updates the given HAR with the actual network information instead of serving from file. The file is written to disk when BrowserContext.close() is called.
-
setUpdateContent
enum RouteFromHarUpdateContentPolicy { EMBED, ATTACH }
(optional) Added in: v1.32#Optional setting to control resource content management. If
attach
is specified, resources are persisted as separate files or entries in the ZIP archive. Ifembed
is specified, content is stored inline the HAR file. -
setUpdateMode
enum HarMode { FULL, MINIMAL }
(optional) Added in: v1.32#When set to
minimal
, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults tominimal
. -
setUrl
String | Pattern (optional)#A glob pattern, regular expression or predicate to match the request URL. Only requests with URL matching the pattern will be served from the HAR file. If not specified, all requests are served from the HAR file.
-
傳回值
routeWebSocket
Added in: v1.48This 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.
使用方式
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();
});
參數
-
url
String | Pattern | Predicate<String>#Only WebSockets with the url matching this pattern will be routed. A string pattern can be relative to the setBaseURL context option.
-
handler
Consumer<WebSocketRoute>#Handler function to route the WebSocket.
傳回值
setDefaultNavigationTimeout
Added before v1.9This 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()
Page.setDefaultNavigationTimeout() and Page.setDefaultTimeout() take priority over BrowserContext.setDefaultNavigationTimeout().
使用方式
BrowserContext.setDefaultNavigationTimeout(timeout);
參數
setDefaultTimeout
Added before v1.9This setting will change the default maximum time for all the methods accepting timeout option.
使用方式
BrowserContext.setDefaultTimeout(timeout);
參數
setExtraHTTPHeaders
Added before v1.9The 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.
BrowserContext.setExtraHTTPHeaders() does not guarantee the order of headers in the outgoing requests.
使用方式
BrowserContext.setExtraHTTPHeaders(headers);
參數
-
An object containing additional HTTP headers to be sent with every request. All header values must be strings.
傳回值
setGeolocation
Added before v1.9Sets the context's geolocation. Passing null
or undefined
emulates position unavailable.
使用方式
browserContext.setGeolocation(new Geolocation(59.95, 30.31667));
Consider using BrowserContext.grantPermissions() to grant permissions for the browser context pages to read its geolocation.
參數
傳回值
setOffline
Added before v1.9使用方式
BrowserContext.setOffline(offline);
參數
傳回值
storageState
Added before v1.9Returns storage state for this browser context, contains current cookies, local storage snapshot and IndexedDB snapshot.
使用方式
BrowserContext.storageState();
BrowserContext.storageState(options);
參數
options
BrowserContext.StorageStateOptions
(optional)-
setIndexedDB
boolean (optional) Added in: v1.51#Set to
true
to include IndexedDB in the storage state snapshot. If your application uses IndexedDB to store authentication tokens, like Firebase Authentication, enable this. -
The file path to save the storage state to. If setPath is a relative path, then it is resolved relative to current working directory. If no path is provided, storage state is still returned, but won't be saved to the disk.
-
傳回值
unroute
Added before v1.9Removes a route created with BrowserContext.route(). When handler is not specified, removes all routes for the url.
使用方式
BrowserContext.unroute(url);
BrowserContext.unroute(url, handler);
參數
-
url
String | Pattern | Predicate<String>#A glob pattern, regex pattern or predicate receiving [URL] used to register a routing with BrowserContext.route().
-
handler
Consumer<Route> (optional)#Optional handler function used to register a routing with BrowserContext.route().
傳回值
unrouteAll
Added in: v1.41Removes all routes created with BrowserContext.route() and BrowserContext.routeFromHAR().
使用方式
BrowserContext.unrouteAll();
傳回值
waitForCondition
Added in: v1.32The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.
使用方式
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);
參數
-
condition
[BooleanSupplier]#Condition to wait for.
-
options
BrowserContext.WaitForConditionOptions
(optional)-
Maximum time to wait for in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.setDefaultTimeout() or Page.setDefaultTimeout() methods.
-
傳回值
waitForConsoleMessage
Added in: v1.34Performs 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.
使用方式
BrowserContext.waitForConsoleMessage(callback);
BrowserContext.waitForConsoleMessage(callback, options);
參數
-
options
BrowserContext.WaitForConsoleMessageOptions
(optional)-
setPredicate
Predicate<ConsoleMessage> (optional)#Receives the ConsoleMessage object and resolves to truthy value when the waiting should resolve.
-
Maximum time to wait for in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.setDefaultTimeout().
-
-
Callback that performs the action triggering the event.
傳回值
waitForPage
Added in: v1.9Performs 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.
使用方式
BrowserContext.waitForPage(callback);
BrowserContext.waitForPage(callback, options);
參數
-
options
BrowserContext.WaitForPageOptions
(optional)-
setPredicate
Predicate<Page> (optional)#Receives the Page object and resolves to truthy value when the waiting should resolve.
-
Maximum time to wait for in milliseconds. Defaults to
30000
(30 seconds). Pass0
to disable timeout. The default value can be changed by using the BrowserContext.setDefaultTimeout().
-
-
Callback that performs the action triggering the event.
傳回值
屬性 (Properties)
clock()
Added in: v1.45Playwright has ability to mock clock and passage of time.
使用方式
BrowserContext.clock()
傳回值
request()
Added in: v1.16API testing helper associated with this context. Requests made with this API will use context cookies.
使用方式
BrowserContext.request()
傳回值
tracing()
Added in: v1.12使用方式
BrowserContext.tracing()
傳回值
事件 (Events)
onBackgroundPage(handler)
Added in: v1.11Only 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());
});
使用方式
BrowserContext.onBackgroundPage(handler)
事件資料
onClose(handler)
Added before v1.9Emitted 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.
使用方式
BrowserContext.onClose(handler)
事件資料
onConsoleMessage(handler)
Added in: v1.34Emitted 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.
使用方式
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' })");
事件資料
onDialog(handler)
Added in: v1.34Emitted 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.
使用方式
context.onDialog(dialog -> {
dialog.accept();
});
When no Page.onDialog(handler) or BrowserContext.onDialog(handler) listeners are present, all dialogs are automatically dismissed.
事件資料
onPage(handler)
Added before v1.9The 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"));
Use Page.waitForLoadState() to wait until the page gets to a particular state (you should not need it in most cases).
使用方式
BrowserContext.onPage(handler)
事件資料
onRequest(handler)
Added in: v1.12Emitted 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().
使用方式
BrowserContext.onRequest(handler)
事件資料
onRequestFailed(handler)
Added in: v1.12Emitted when a request fails, for example by timing out. To only listen for failed requests from a particular page, use Page.onRequestFailed(handler).
HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with BrowserContext.onRequestFinished(handler) event and not with BrowserContext.onRequestFailed(handler).
使用方式
BrowserContext.onRequestFailed(handler)
事件資料
onRequestFinished(handler)
Added in: v1.12Emitted 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).
使用方式
BrowserContext.onRequestFinished(handler)
事件資料
onResponse(handler)
Added in: v1.12Emitted 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).
使用方式
BrowserContext.onResponse(handler)
事件資料
onWebError(handler)
Added in: v1.38Emitted 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.
使用方式
BrowserContext.onWebError(handler)
事件資料