public interface Page extends AutoCloseable
Browser
, or an extension background page in Chromium. One Browser
instance might have multiple Page
instances.
This example creates a page, navigates it to a URL, and then saves a screenshot:
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();
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.navigate("https://example.com");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
browser.close();
}
}
}
The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter
methods, such as on
, once
or
removeListener
.
This example logs a message for a single page load
event:
page.onLoad(p -> System.out.println("Page loaded!"));
To unsubscribe from events use the removeListener
method:
Consumer<Request> logRequest = interceptedRequest -> {
System.out.println("A request was made: " + interceptedRequest.url());
};
page.onRequest(logRequest);
// Sometime later...
page.offRequest(logRequest);
Modifier and Type | Method and Description |
---|---|
void |
addInitScript(Path script)
Adds a script which would be evaluated in one of the following scenarios:
Whenever the page is navigated.
Whenever the child frame is attached or navigated.
|
void |
addInitScript(String script)
Adds a script which would be evaluated in one of the following scenarios:
Whenever the page is navigated.
Whenever the child frame is attached or navigated.
|
default ElementHandle |
addScriptTag()
Adds a
<script> tag into the page with the desired url or content. |
ElementHandle |
addScriptTag(Page.AddScriptTagOptions options)
Adds a
<script> tag into the page with the desired url or content. |
default ElementHandle |
addStyleTag()
Adds a
<link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the
content. |
ElementHandle |
addStyleTag(Page.AddStyleTagOptions options)
Adds a
<link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the
content. |
void |
bringToFront()
Brings page to front (activates tab).
|
default void |
check(String selector)
This method checks an element matching
selector by performing the following steps:
Find an element matching selector . |
void |
check(String selector,
Page.CheckOptions options)
This method checks an element matching
selector by performing the following steps:
Find an element matching selector . |
default void |
click(String selector)
This method clicks an element matching
selector by performing the following steps:
Find an element matching selector . |
void |
click(String selector,
Page.ClickOptions options)
This method clicks an element matching
selector by performing the following steps:
Find an element matching selector . |
default void |
close()
If
runBeforeUnload is false , does not run any unload handlers and waits for the page to be closed. |
void |
close(Page.CloseOptions options)
If
runBeforeUnload is false , does not run any unload handlers and waits for the page to be closed. |
String |
content()
Gets the full HTML contents of the page, including the doctype.
|
BrowserContext |
context()
Get the browser context that the page belongs to.
|
default void |
dblclick(String selector)
This method double clicks an element matching
selector by performing the following steps:
Find an element matching selector . |
void |
dblclick(String selector,
Page.DblclickOptions options)
This method double clicks an element matching
selector by performing the following steps:
Find an element matching selector . |
default void |
dispatchEvent(String selector,
String type)
The snippet below dispatches the
click event on the element. |
default void |
dispatchEvent(String selector,
String type,
Object eventInit)
The snippet below dispatches the
click event on the element. |
void |
dispatchEvent(String selector,
String type,
Object eventInit,
Page.DispatchEventOptions options)
The snippet below dispatches the
click event on the element. |
default void |
emulateMedia()
This method changes the
CSS media type through the media argument, and/or the "prefers-colors-scheme" media
feature, using the colorScheme argument. |
void |
emulateMedia(Page.EmulateMediaOptions options)
This method changes the
CSS media type through the media argument, and/or the "prefers-colors-scheme" media
feature, using the colorScheme argument. |
default Object |
evalOnSelector(String selector,
String expression)
The method finds an element matching the specified selector within the page and passes it as a first argument to
expression . |
Object |
evalOnSelector(String selector,
String expression,
Object arg)
The method finds an element matching the specified selector within the page and passes it as a first argument to
expression . |
default Object |
evalOnSelectorAll(String selector,
String expression)
The method finds all elements matching the specified selector within the page and passes an array of matched elements as
a first argument to
expression . |
Object |
evalOnSelectorAll(String selector,
String expression,
Object arg)
The method finds all elements matching the specified selector within the page and passes an array of matched elements as
a first argument to
expression . |
default Object |
evaluate(String expression)
Returns the value of the
expression invocation. |
Object |
evaluate(String expression,
Object arg)
Returns the value of the
expression invocation. |
default JSHandle |
evaluateHandle(String expression)
Returns the value of the
expression invocation as a JSHandle . |
JSHandle |
evaluateHandle(String expression,
Object arg)
Returns the value of the
expression invocation as a JSHandle . |
default void |
exposeBinding(String name,
BindingCallback callback)
The method adds a function called
name on the window object of every frame in this page. |
void |
exposeBinding(String name,
BindingCallback callback,
Page.ExposeBindingOptions options)
The method adds a function called
name on the window object of every frame in this page. |
void |
exposeFunction(String name,
FunctionCallback callback)
The method adds a function called
name on the window object of every frame in the page. |
default void |
fill(String selector,
String value)
This method waits for an element matching
selector , waits for actionability checks, focuses the element, fills it and
triggers an input event after filling. |
void |
fill(String selector,
String value,
Page.FillOptions options)
This method waits for an element matching
selector , waits for actionability checks, focuses the element, fills it and
triggers an input event after filling. |
default void |
focus(String selector)
This method fetches an element with
selector and focuses it. |
void |
focus(String selector,
Page.FocusOptions options)
This method fetches an element with
selector and focuses it. |
Frame |
frame(String name)
Returns frame matching the specified criteria.
|
Frame |
frameByUrl(Pattern url)
Returns frame with matching URL.
|
Frame |
frameByUrl(Predicate<String> url)
Returns frame with matching URL.
|
Frame |
frameByUrl(String url)
Returns frame with matching URL.
|
List<Frame> |
frames()
An array of all frames attached to the page.
|
default String |
getAttribute(String selector,
String name)
Returns element attribute value.
|
String |
getAttribute(String selector,
String name,
Page.GetAttributeOptions options)
Returns element attribute value.
|
default Response |
goBack()
Returns the main resource response.
|
Response |
goBack(Page.GoBackOptions options)
Returns the main resource response.
|
default Response |
goForward()
Returns the main resource response.
|
Response |
goForward(Page.GoForwardOptions options)
Returns the main resource response.
|
default void |
hover(String selector)
This method hovers over an element matching
selector by performing the following steps:
Find an element matching selector . |
void |
hover(String selector,
Page.HoverOptions options)
This method hovers over an element matching
selector by performing the following steps:
Find an element matching selector . |
default String |
innerHTML(String selector)
Returns
element.innerHTML . |
String |
innerHTML(String selector,
Page.InnerHTMLOptions options)
Returns
element.innerHTML . |
default String |
innerText(String selector)
Returns
element.innerText . |
String |
innerText(String selector,
Page.InnerTextOptions options)
Returns
element.innerText . |
default boolean |
isChecked(String selector)
Returns whether the element is checked.
|
boolean |
isChecked(String selector,
Page.IsCheckedOptions options)
Returns whether the element is checked.
|
boolean |
isClosed()
Indicates that the page has been closed.
|
default boolean |
isDisabled(String selector)
Returns whether the element is disabled, the opposite of enabled.
|
boolean |
isDisabled(String selector,
Page.IsDisabledOptions options)
Returns whether the element is disabled, the opposite of enabled.
|
default boolean |
isEditable(String selector)
Returns whether the element is editable.
|
boolean |
isEditable(String selector,
Page.IsEditableOptions options)
Returns whether the element is editable.
|
default boolean |
isEnabled(String selector)
Returns whether the element is enabled.
|
boolean |
isEnabled(String selector,
Page.IsEnabledOptions options)
Returns whether the element is enabled.
|
default boolean |
isHidden(String selector)
Returns whether the element is hidden, the opposite of visible.
|
boolean |
isHidden(String selector,
Page.IsHiddenOptions options)
Returns whether the element is hidden, the opposite of visible.
|
default boolean |
isVisible(String selector)
Returns whether the element is visible.
|
boolean |
isVisible(String selector,
Page.IsVisibleOptions options)
Returns whether the element is visible.
|
Keyboard |
keyboard() |
Frame |
mainFrame()
The page's main frame.
|
Mouse |
mouse() |
default Response |
navigate(String url)
Returns the main resource response.
|
Response |
navigate(String url,
Page.NavigateOptions options)
Returns the main resource response.
|
void |
offClose(Consumer<Page> handler)
Removes handler that was previously added with
onClose(handler) . |
void |
offConsoleMessage(Consumer<ConsoleMessage> handler)
Removes handler that was previously added with
onConsoleMessage(handler) . |
void |
offCrash(Consumer<Page> handler)
Removes handler that was previously added with
onCrash(handler) . |
void |
offDialog(Consumer<Dialog> handler)
Removes handler that was previously added with
onDialog(handler) . |
void |
offDOMContentLoaded(Consumer<Page> handler)
Removes handler that was previously added with
onDOMContentLoaded(handler) . |
void |
offDownload(Consumer<Download> handler)
Removes handler that was previously added with
onDownload(handler) . |
void |
offFileChooser(Consumer<FileChooser> handler)
Removes handler that was previously added with
onFileChooser(handler) . |
void |
offFrameAttached(Consumer<Frame> handler)
Removes handler that was previously added with
onFrameAttached(handler) . |
void |
offFrameDetached(Consumer<Frame> handler)
Removes handler that was previously added with
onFrameDetached(handler) . |
void |
offFrameNavigated(Consumer<Frame> handler)
Removes handler that was previously added with
onFrameNavigated(handler) . |
void |
offLoad(Consumer<Page> handler)
Removes handler that was previously added with
onLoad(handler) . |
void |
offPageError(Consumer<String> handler)
Removes handler that was previously added with
onPageError(handler) . |
void |
offPopup(Consumer<Page> handler)
Removes handler that was previously added with
onPopup(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 |
offWebSocket(Consumer<WebSocket> handler)
Removes handler that was previously added with
onWebSocket(handler) . |
void |
offWorker(Consumer<Worker> handler)
Removes handler that was previously added with
onWorker(handler) . |
void |
onceDialog(Consumer<Dialog> handler)
Adds one-off
Dialog handler. |
void |
onClose(Consumer<Page> handler)
Emitted when the page closes.
|
void |
onConsoleMessage(Consumer<ConsoleMessage> handler)
Emitted when JavaScript within the page calls one of console API methods, e.g.
|
void |
onCrash(Consumer<Page> handler)
Emitted when the page crashes.
|
void |
onDialog(Consumer<Dialog> handler)
Emitted when a JavaScript dialog appears, such as
alert , prompt , confirm or beforeunload . |
void |
onDOMContentLoaded(Consumer<Page> handler)
Emitted when the JavaScript
DOMContentLoaded event is dispatched. |
void |
onDownload(Consumer<Download> handler)
Emitted when attachment download started.
|
void |
onFileChooser(Consumer<FileChooser> handler)
Emitted when a file chooser is supposed to appear, such as after clicking the
<input type=file> . |
void |
onFrameAttached(Consumer<Frame> handler)
Emitted when a frame is attached.
|
void |
onFrameDetached(Consumer<Frame> handler)
Emitted when a frame is detached.
|
void |
onFrameNavigated(Consumer<Frame> handler)
Emitted when a frame is navigated to a new url.
|
void |
onLoad(Consumer<Page> handler)
Emitted when the JavaScript
load event is
dispatched. |
void |
onPageError(Consumer<String> handler)
Emitted when an uncaught exception happens within the page.
|
void |
onPopup(Consumer<Page> handler)
Emitted when the page opens a new tab or window.
|
void |
onRequest(Consumer<Request> handler)
Emitted when a page issues a request.
|
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 |
onWebSocket(Consumer<WebSocket> handler)
Emitted when
WebSocket request is sent. |
void |
onWorker(Consumer<Worker> handler)
Emitted when a dedicated WebWorker is
spawned by the page.
|
Page |
opener()
Returns the opener for popup pages and
null for others. |
void |
pause()
Pauses script execution.
|
default byte[] |
pdf()
Returns the PDF buffer.
|
byte[] |
pdf(Page.PdfOptions options)
Returns the PDF buffer.
|
default void |
press(String selector,
String key)
Focuses the element, and then uses
Keyboard.down() and Keyboard.up() . |
void |
press(String selector,
String key,
Page.PressOptions options)
Focuses the element, and then uses
Keyboard.down() and Keyboard.up() . |
ElementHandle |
querySelector(String selector)
The method finds an element matching the specified selector within the page.
|
List<ElementHandle> |
querySelectorAll(String selector)
The method finds all elements matching the specified selector within the page.
|
default Response |
reload()
Returns the main resource response.
|
Response |
reload(Page.ReloadOptions options)
Returns the main resource response.
|
void |
route(Pattern url,
Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by a page.
|
void |
route(Predicate<String> url,
Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by a page.
|
void |
route(String url,
Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by a page.
|
default byte[] |
screenshot()
Returns the buffer with the captured screenshot.
|
byte[] |
screenshot(Page.ScreenshotOptions options)
Returns the buffer with the captured screenshot.
|
default List<String> |
selectOption(String selector,
ElementHandle values)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
default List<String> |
selectOption(String selector,
ElementHandle[] values)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
List<String> |
selectOption(String selector,
ElementHandle[] values,
Page.SelectOptionOptions options)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
List<String> |
selectOption(String selector,
ElementHandle values,
Page.SelectOptionOptions options)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
default List<String> |
selectOption(String selector,
SelectOption values)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
default List<String> |
selectOption(String selector,
SelectOption[] values)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
List<String> |
selectOption(String selector,
SelectOption[] values,
Page.SelectOptionOptions options)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
List<String> |
selectOption(String selector,
SelectOption values,
Page.SelectOptionOptions options)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
default List<String> |
selectOption(String selector,
String values)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
default List<String> |
selectOption(String selector,
String[] values)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
List<String> |
selectOption(String selector,
String[] values,
Page.SelectOptionOptions options)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
List<String> |
selectOption(String selector,
String values,
Page.SelectOptionOptions options)
This method waits for an element matching
selector , waits for actionability checks, waits until all specified options are
present in the <select> element and selects these options. |
default void |
setContent(String html) |
void |
setContent(String html,
Page.SetContentOptions options) |
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.goto()
Page.reload()
Page.setContent()
Page.waitForNavigation()
Page.waitForURL()
|
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 the page initiates.
|
default void |
setInputFiles(String selector,
FilePayload files)
This method expects
selector to point to an input element. |
default void |
setInputFiles(String selector,
FilePayload[] files)
This method expects
selector to point to an input element. |
void |
setInputFiles(String selector,
FilePayload[] files,
Page.SetInputFilesOptions options)
This method expects
selector to point to an input element. |
void |
setInputFiles(String selector,
FilePayload files,
Page.SetInputFilesOptions options)
This method expects
selector to point to an input element. |
default void |
setInputFiles(String selector,
Path files)
This method expects
selector to point to an input element. |
default void |
setInputFiles(String selector,
Path[] files)
This method expects
selector to point to an input element. |
void |
setInputFiles(String selector,
Path[] files,
Page.SetInputFilesOptions options)
This method expects
selector to point to an input element. |
void |
setInputFiles(String selector,
Path files,
Page.SetInputFilesOptions options)
This method expects
selector to point to an input element. |
void |
setViewportSize(int width,
int height)
In the case of multiple pages in a single browser, each page can have its own viewport size.
|
default void |
tap(String selector)
This method taps an element matching
selector by performing the following steps:
Find an element matching selector . |
void |
tap(String selector,
Page.TapOptions options)
This method taps an element matching
selector by performing the following steps:
Find an element matching selector . |
default String |
textContent(String selector)
Returns
element.textContent . |
String |
textContent(String selector,
Page.TextContentOptions options)
Returns
element.textContent . |
String |
title()
Returns the page's title.
|
Touchscreen |
touchscreen() |
default void |
type(String selector,
String text)
Sends a
keydown , keypress /input , and keyup event for each character in the text. |
void |
type(String selector,
String text,
Page.TypeOptions options)
Sends a
keydown , keypress /input , and keyup event for each character in the text. |
default void |
uncheck(String selector)
This method unchecks an element matching
selector by performing the following steps:
Find an element matching selector . |
void |
uncheck(String selector,
Page.UncheckOptions options)
This method unchecks an element matching
selector by performing the following steps:
Find an element matching selector . |
default void |
unroute(Pattern url)
Removes a route created with
Page.route() . |
void |
unroute(Pattern url,
Consumer<Route> handler)
Removes a route created with
Page.route() . |
default void |
unroute(Predicate<String> url)
Removes a route created with
Page.route() . |
void |
unroute(Predicate<String> url,
Consumer<Route> handler)
Removes a route created with
Page.route() . |
default void |
unroute(String url)
Removes a route created with
Page.route() . |
void |
unroute(String url,
Consumer<Route> handler)
Removes a route created with
Page.route() . |
String |
url()
Shortcut for main frame's
Frame.url() . |
Video |
video()
Video object associated with this page.
|
ViewportSize |
viewportSize() |
Page |
waitForClose(Page.WaitForCloseOptions options,
Runnable callback)
Performs action and waits for the Page to close.
|
default Page |
waitForClose(Runnable callback)
Performs action and waits for the Page to close.
|
ConsoleMessage |
waitForConsoleMessage(Page.WaitForConsoleMessageOptions options,
Runnable callback)
Performs action and waits for a
ConsoleMessage to be logged by in the page. |
default ConsoleMessage |
waitForConsoleMessage(Runnable callback)
Performs action and waits for a
ConsoleMessage to be logged by in the page. |
Download |
waitForDownload(Page.WaitForDownloadOptions options,
Runnable callback)
Performs action and waits for a new
Download . |
default Download |
waitForDownload(Runnable callback)
Performs action and waits for a new
Download . |
FileChooser |
waitForFileChooser(Page.WaitForFileChooserOptions options,
Runnable callback)
Performs action and waits for a new
FileChooser to be created. |
default FileChooser |
waitForFileChooser(Runnable callback)
Performs action and waits for a new
FileChooser to be created. |
default JSHandle |
waitForFunction(String expression)
Returns when the
expression returns a truthy value. |
default JSHandle |
waitForFunction(String expression,
Object arg)
Returns when the
expression returns a truthy value. |
JSHandle |
waitForFunction(String expression,
Object arg,
Page.WaitForFunctionOptions options)
Returns when the
expression returns a truthy value. |
default void |
waitForLoadState()
Returns when the required load state has been reached.
|
default void |
waitForLoadState(LoadState state)
Returns when the required load state has been reached.
|
void |
waitForLoadState(LoadState state,
Page.WaitForLoadStateOptions options)
Returns when the required load state has been reached.
|
Response |
waitForNavigation(Page.WaitForNavigationOptions options,
Runnable callback)
Waits for the main frame navigation and returns the main resource response.
|
default Response |
waitForNavigation(Runnable callback)
Waits for the main frame navigation and returns the main resource response.
|
Page |
waitForPopup(Page.WaitForPopupOptions options,
Runnable callback)
Performs action and waits for a popup
Page . |
default Page |
waitForPopup(Runnable callback)
Performs action and waits for a popup
Page . |
Request |
waitForRequest(Pattern urlOrPredicate,
Page.WaitForRequestOptions options,
Runnable callback)
Waits for the matching request and returns it.
|
default Request |
waitForRequest(Pattern urlOrPredicate,
Runnable callback)
Waits for the matching request and returns it.
|
Request |
waitForRequest(Predicate<Request> urlOrPredicate,
Page.WaitForRequestOptions options,
Runnable callback)
Waits for the matching request and returns it.
|
default Request |
waitForRequest(Predicate<Request> urlOrPredicate,
Runnable callback)
Waits for the matching request and returns it.
|
Request |
waitForRequest(String urlOrPredicate,
Page.WaitForRequestOptions options,
Runnable callback)
Waits for the matching request and returns it.
|
default Request |
waitForRequest(String urlOrPredicate,
Runnable callback)
Waits for the matching request and returns it.
|
Request |
waitForRequestFinished(Page.WaitForRequestFinishedOptions options,
Runnable callback)
Performs action and waits for a
Request to finish loading. |
default Request |
waitForRequestFinished(Runnable callback)
Performs action and waits for a
Request to finish loading. |
Response |
waitForResponse(Pattern urlOrPredicate,
Page.WaitForResponseOptions options,
Runnable callback)
Returns the matched response.
|
default Response |
waitForResponse(Pattern urlOrPredicate,
Runnable callback)
Returns the matched response.
|
Response |
waitForResponse(Predicate<Response> urlOrPredicate,
Page.WaitForResponseOptions options,
Runnable callback)
Returns the matched response.
|
default Response |
waitForResponse(Predicate<Response> urlOrPredicate,
Runnable callback)
Returns the matched response.
|
Response |
waitForResponse(String urlOrPredicate,
Page.WaitForResponseOptions options,
Runnable callback)
Returns the matched response.
|
default Response |
waitForResponse(String urlOrPredicate,
Runnable callback)
Returns the matched response.
|
default ElementHandle |
waitForSelector(String selector)
Returns when element specified by selector satisfies
state option. |
ElementHandle |
waitForSelector(String selector,
Page.WaitForSelectorOptions options)
Returns when element specified by selector satisfies
state option. |
void |
waitForTimeout(double timeout)
Waits for the given
timeout in milliseconds. |
default void |
waitForURL(Pattern url)
Waits for the main frame to navigate to the given URL.
|
void |
waitForURL(Pattern url,
Page.WaitForURLOptions options)
Waits for the main frame to navigate to the given URL.
|
default void |
waitForURL(Predicate<String> url)
Waits for the main frame to navigate to the given URL.
|
void |
waitForURL(Predicate<String> url,
Page.WaitForURLOptions options)
Waits for the main frame to navigate to the given URL.
|
default void |
waitForURL(String url)
Waits for the main frame to navigate to the given URL.
|
void |
waitForURL(String url,
Page.WaitForURLOptions options)
Waits for the main frame to navigate to the given URL.
|
WebSocket |
waitForWebSocket(Page.WaitForWebSocketOptions options,
Runnable callback)
Performs action and waits for a new
WebSocket . |
default WebSocket |
waitForWebSocket(Runnable callback)
Performs action and waits for a new
WebSocket . |
Worker |
waitForWorker(Page.WaitForWorkerOptions options,
Runnable callback)
Performs action and waits for a new
Worker . |
default Worker |
waitForWorker(Runnable callback)
Performs action and waits for a new
Worker . |
List<Worker> |
workers()
This method returns all of the dedicated WebWorkers associated with the page.
|
void offClose(Consumer<Page> handler)
onClose(handler)
.void onConsoleMessage(Consumer<ConsoleMessage> handler)
console.log
or console.dir
. Also
emitted if the page throws an error or a warning.
The arguments passed into console.log
appear as arguments on the event handler.
An example of handling console
event:
page.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'})");
void offConsoleMessage(Consumer<ConsoleMessage> handler)
onConsoleMessage(handler)
.void onCrash(Consumer<Page> handler)
The most common way to deal with crashes is to catch an exception:
try {
// Crash might happen during a click.
page.click("button");
// Or while waiting for an event.
page.waitForPopup(() -> {});
} catch (PlaywrightException e) {
// When the page crashes, exception message contains "crash".
}
void offCrash(Consumer<Page> handler)
onCrash(handler)
.void onDialog(Consumer<Dialog> handler)
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.
NOTE: When no Page.onDialog()
listeners are present, all dialogs are automatically dismissed.
void offDialog(Consumer<Dialog> handler)
onDialog(handler)
.void onDOMContentLoaded(Consumer<Page> handler)
DOMContentLoaded
event is dispatched.void offDOMContentLoaded(Consumer<Page> handler)
onDOMContentLoaded(handler)
.void onDownload(Consumer<Download> handler)
Download
instance.
NOTE: Browser context **must** be created with the acceptDownloads
set to true
when user needs access to the downloaded
content. If acceptDownloads
is not set, download events are emitted, but the actual download is not performed and user
has no access to the downloaded files.
void offDownload(Consumer<Download> handler)
onDownload(handler)
.void onFileChooser(Consumer<FileChooser> handler)
<input type=file>
. Playwright can
respond to it via setting the input files using FileChooser.setFiles()
that can be uploaded
after that.
page.onFileChooser(fileChooser -> {
fileChooser.setFiles(Paths.get("/tmp/myfile.pdf"));
});
void offFileChooser(Consumer<FileChooser> handler)
onFileChooser(handler)
.void offFrameAttached(Consumer<Frame> handler)
onFrameAttached(handler)
.void offFrameDetached(Consumer<Frame> handler)
onFrameDetached(handler)
.void onFrameNavigated(Consumer<Frame> handler)
void offFrameNavigated(Consumer<Frame> handler)
onFrameNavigated(handler)
.void offLoad(Consumer<Page> handler)
onLoad(handler)
.void onPageError(Consumer<String> handler)
void offPageError(Consumer<String> handler)
onPageError(handler)
.void onPopup(Consumer<Page> handler)
BrowserContext.onPage()
, but only for popups relevant to this 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 popup = page.waitForPopup(() -> {
page.evaluate("() => window.open('https://example.com')");
});
System.out.println(popup.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 offPopup(Consumer<Page> handler)
onPopup(handler)
.void onRequest(Consumer<Request> handler)
Page.route()
or BrowserContext.route()
.void offRequest(Consumer<Request> handler)
onRequest(handler)
.void onRequestFailed(Consumer<Request> handler)
NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete
with Page.onRequestFinished()
event and not with Page.onRequestFailed()
. A request will only be considered failed when the client cannot get an HTTP response from the
server, e.g. due to network error net::ERR_FAILED.
void offRequestFailed(Consumer<Request> handler)
onRequestFailed(handler)
.void onRequestFinished(Consumer<Request> handler)
request
, response
and requestfinished
.void offRequestFinished(Consumer<Request> handler)
onRequestFinished(handler)
.void onResponse(Consumer<Response> handler)
request
, response
and requestfinished
.void offResponse(Consumer<Response> handler)
onResponse(handler)
.void offWebSocket(Consumer<WebSocket> handler)
onWebSocket(handler)
.void onWorker(Consumer<Worker> handler)
void offWorker(Consumer<Worker> handler)
onWorker(handler)
.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
page.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
page.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.default ElementHandle addScriptTag()
<script>
tag into the page with the desired url or content. Returns the added tag when the script's onload
fires or when the script content was injected into frame.
Shortcut for main frame's Frame.addScriptTag()
.
ElementHandle addScriptTag(Page.AddScriptTagOptions options)
<script>
tag into the page with the desired url or content. Returns the added tag when the script's onload
fires or when the script content was injected into frame.
Shortcut for main frame's Frame.addScriptTag()
.
default ElementHandle addStyleTag()
<link rel="stylesheet">
tag into the page with the desired url or a <style type="text/css">
tag with the
content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
Shortcut for main frame's Frame.addStyleTag()
.
ElementHandle addStyleTag(Page.AddStyleTagOptions options)
<link rel="stylesheet">
tag into the page with the desired url or a <style type="text/css">
tag with the
content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
Shortcut for main frame's Frame.addStyleTag()
.
void bringToFront()
default void check(String selector)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to click in the center of the element.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.check()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void check(String selector, Page.CheckOptions options)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to click in the center of the element.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.check()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void click(String selector)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to click in the center of the element, or the specified position
.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.click()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void click(String selector, Page.ClickOptions options)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to click in the center of the element, or the specified position
.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.click()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void close()
runBeforeUnload
is false
, does not run any unload handlers and waits for the page to be closed. If
runBeforeUnload
is true
the method will run unload handlers, but will **not** wait for the page to close.
By default, page.close()
**does not** run beforeunload
handlers.
NOTE: if runBeforeUnload
is passed as true, a beforeunload
dialog might be summoned and should be handled manually via
Page.onDialog()
event.
close
in interface AutoCloseable
void close(Page.CloseOptions options)
runBeforeUnload
is false
, does not run any unload handlers and waits for the page to be closed. If
runBeforeUnload
is true
the method will run unload handlers, but will **not** wait for the page to close.
By default, page.close()
**does not** run beforeunload
handlers.
NOTE: if runBeforeUnload
is passed as true, a beforeunload
dialog might be summoned and should be handled manually via
Page.onDialog()
event.
String content()
BrowserContext context()
default void dblclick(String selector)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to double click in the center of the element, or the specified position
.noWaitAfter
option is set. Note that if the first
click of the dblclick()
triggers a navigation event, this method will throw. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
NOTE: page.dblclick()
dispatches two click
events and a single dblclick
event.
Shortcut for main frame's Frame.dblclick()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void dblclick(String selector, Page.DblclickOptions options)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to double click in the center of the element, or the specified position
.noWaitAfter
option is set. Note that if the first
click of the dblclick()
triggers a navigation event, this method will throw. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
NOTE: page.dblclick()
dispatches two click
events and a single dblclick
event.
Shortcut for main frame's Frame.dblclick()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void dispatchEvent(String selector, String type, Object eventInit)
click
event on the element. Regardless of the visibility state of the element,
click
is dispatched. This is equivalent to calling element.click().
page.dispatchEvent("button#submit", "click");
Under the hood, it creates an instance of an event based on the given type
, initializes it with eventInit
properties
and dispatches it on the element. Events are composed
, cancelable
and bubble by default.
Since eventInit
is event-specific, please refer to the events documentation for the lists of initial properties:
You can also specify JSHandle
as the property value if you want live objects to be passed into the event:
// Note you can only create DataTransfer in Chromium and Firefox
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
page.dispatchEvent("#source", "dragstart", arg);
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.type
- DOM event type: "click"
, "dragstart"
, etc.eventInit
- Optional event-specific initialization properties.default void dispatchEvent(String selector, String type)
click
event on the element. Regardless of the visibility state of the element,
click
is dispatched. This is equivalent to calling element.click().
page.dispatchEvent("button#submit", "click");
Under the hood, it creates an instance of an event based on the given type
, initializes it with eventInit
properties
and dispatches it on the element. Events are composed
, cancelable
and bubble by default.
Since eventInit
is event-specific, please refer to the events documentation for the lists of initial properties:
You can also specify JSHandle
as the property value if you want live objects to be passed into the event:
// Note you can only create DataTransfer in Chromium and Firefox
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
page.dispatchEvent("#source", "dragstart", arg);
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.type
- DOM event type: "click"
, "dragstart"
, etc.void dispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options)
click
event on the element. Regardless of the visibility state of the element,
click
is dispatched. This is equivalent to calling element.click().
page.dispatchEvent("button#submit", "click");
Under the hood, it creates an instance of an event based on the given type
, initializes it with eventInit
properties
and dispatches it on the element. Events are composed
, cancelable
and bubble by default.
Since eventInit
is event-specific, please refer to the events documentation for the lists of initial properties:
You can also specify JSHandle
as the property value if you want live objects to be passed into the event:
// Note you can only create DataTransfer in Chromium and Firefox
JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
Map<String, Object> arg = new HashMap<>();
arg.put("dataTransfer", dataTransfer);
page.dispatchEvent("#source", "dragstart", arg);
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.type
- DOM event type: "click"
, "dragstart"
, etc.eventInit
- Optional event-specific initialization properties.default void emulateMedia()
CSS media type
through the media
argument, and/or the "prefers-colors-scheme"
media
feature, using the colorScheme
argument.
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));
page.evaluate("() => matchMedia('screen').matches");
// → false
page.evaluate("() => matchMedia('print').matches");
// → true
page.emulateMedia(new Page.EmulateMediaOptions());
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches");
// → true
page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
// → false
page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches");
// → false
void emulateMedia(Page.EmulateMediaOptions options)
CSS media type
through the media
argument, and/or the "prefers-colors-scheme"
media
feature, using the colorScheme
argument.
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT));
page.evaluate("() => matchMedia('screen').matches");
// → false
page.evaluate("() => matchMedia('print').matches");
// → true
page.emulateMedia(new Page.EmulateMediaOptions());
page.evaluate("() => matchMedia('screen').matches");
// → true
page.evaluate("() => matchMedia('print').matches");
// → false
page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches");
// → true
page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
// → false
page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches");
// → false
default Object evalOnSelector(String selector, String expression)
expression
. If no elements match the selector, the method throws an error. Returns the value of expression
.
If expression
returns a Promise, then Page.evalOnSelector()
would wait for the promise to resolve and return its value.
Examples:
String searchValue = (String) page.evalOnSelector("#search", "el => el.value");
String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href");
String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");
Shortcut for main frame's Frame.evalOnSelector()
.
selector
- A selector to query for. See working with selectors for more
details.expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.Object evalOnSelector(String selector, String expression, Object arg)
expression
. If no elements match the selector, the method throws an error. Returns the value of expression
.
If expression
returns a Promise, then Page.evalOnSelector()
would wait for the promise to resolve and return its value.
Examples:
String searchValue = (String) page.evalOnSelector("#search", "el => el.value");
String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href");
String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");
Shortcut for main frame's Frame.evalOnSelector()
.
selector
- A selector to query for. See working with selectors for more
details.expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.arg
- Optional argument to pass to expression
.default Object evalOnSelectorAll(String selector, String expression)
expression
. Returns the result of expression
invocation.
If expression
returns a Promise, then Page.evalOnSelectorAll()
would wait for the promise to resolve and return its value.
Examples:
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);
selector
- A selector to query for. See working with selectors for more
details.expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.Object evalOnSelectorAll(String selector, String expression, Object arg)
expression
. Returns the result of expression
invocation.
If expression
returns a Promise, then Page.evalOnSelectorAll()
would wait for the promise to resolve and return its value.
Examples:
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);
selector
- A selector to query for. See working with selectors for more
details.expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.arg
- Optional argument to pass to expression
.default Object evaluate(String expression)
expression
invocation.
If the function passed to the Page.evaluate()
returns a Promise, then Page.evaluate()
would wait for the promise to resolve and return its value.
If the function passed to the Page.evaluate()
returns a non-[Serializable] value, then Page.evaluate()
resolves to undefined
. Playwright also supports transferring some additional values
that are not serializable by JSON
: -0
, NaN
, Infinity
, -Infinity
.
Passing argument to expression
:
Object result = page.evaluate("([x, y]) => {\n" +
" return Promise.resolve(x * y);\n" +
"}", Arrays.asList(7, 8));
System.out.println(result); // prints "56"
A string can also be passed in instead of a function:
System.out.println(page.evaluate("1 + 2")); // prints "3"
ElementHandle
instances can be passed as an argument to the Page.evaluate()
:
ElementHandle bodyHandle = page.querySelector("body");
String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello"));
bodyHandle.dispose();
Shortcut for main frame's Frame.evaluate()
.
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.Object evaluate(String expression, Object arg)
expression
invocation.
If the function passed to the Page.evaluate()
returns a Promise, then Page.evaluate()
would wait for the promise to resolve and return its value.
If the function passed to the Page.evaluate()
returns a non-[Serializable] value, then Page.evaluate()
resolves to undefined
. Playwright also supports transferring some additional values
that are not serializable by JSON
: -0
, NaN
, Infinity
, -Infinity
.
Passing argument to expression
:
Object result = page.evaluate("([x, y]) => {\n" +
" return Promise.resolve(x * y);\n" +
"}", Arrays.asList(7, 8));
System.out.println(result); // prints "56"
A string can also be passed in instead of a function:
System.out.println(page.evaluate("1 + 2")); // prints "3"
ElementHandle
instances can be passed as an argument to the Page.evaluate()
:
ElementHandle bodyHandle = page.querySelector("body");
String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello"));
bodyHandle.dispose();
Shortcut for main frame's Frame.evaluate()
.
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.arg
- Optional argument to pass to expression
.default JSHandle evaluateHandle(String expression)
expression
invocation as a JSHandle
.
The only difference between Page.evaluate()
and Page.evaluateHandle()
is that Page.evaluateHandle()
returns JSHandle
.
If the function passed to the Page.evaluateHandle()
returns a Promise, then Page.evaluateHandle()
would wait for the promise to resolve and return its value.
// Handle for the window object.
JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)");
A string can also be passed in instead of a function:
JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document".
JSHandle
instances can be passed as an argument to the Page.evaluateHandle()
:
JSHandle aHandle = page.evaluateHandle("() => document.body");
JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello"));
System.out.println(resultHandle.jsonValue());
resultHandle.dispose();
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.JSHandle evaluateHandle(String expression, Object arg)
expression
invocation as a JSHandle
.
The only difference between Page.evaluate()
and Page.evaluateHandle()
is that Page.evaluateHandle()
returns JSHandle
.
If the function passed to the Page.evaluateHandle()
returns a Promise, then Page.evaluateHandle()
would wait for the promise to resolve and return its value.
// Handle for the window object.
JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)");
A string can also be passed in instead of a function:
JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document".
JSHandle
instances can be passed as an argument to the Page.evaluateHandle()
:
JSHandle aHandle = page.evaluateHandle("() => document.body");
JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello"));
System.out.println(resultHandle.jsonValue());
resultHandle.dispose();
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.arg
- Optional argument to pass to expression
.default void exposeBinding(String name, BindingCallback callback)
name
on the window
object of every frame in this page. 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 BrowserContext.exposeBinding()
for the context-wide version.
NOTE: Functions installed via Page.exposeBinding()
survive navigations.
An example of exposing page URL to all frames in a page:
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({ headless: false });
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.exposeBinding("pageURL", (source, args) -> source.page().url());
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.click("button");
}
}
}
An example of passing an element handle:
page.exposeBinding("clicked", (source, args) -> {
ElementHandle element = (ElementHandle) args[0];
System.out.println(element.textContent());
return null;
}, new Page.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, Page.ExposeBindingOptions options)
name
on the window
object of every frame in this page. 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 BrowserContext.exposeBinding()
for the context-wide version.
NOTE: Functions installed via Page.exposeBinding()
survive navigations.
An example of exposing page URL to all frames in a page:
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({ headless: false });
BrowserContext context = browser.newContext();
Page page = context.newPage();
page.exposeBinding("pageURL", (source, args) -> source.page().url());
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.click("button");
}
}
}
An example of passing an element handle:
page.exposeBinding("clicked", (source, args) -> {
ElementHandle element = (ElementHandle) args[0];
System.out.println(element.textContent());
return null;
}, new Page.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 the page. 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 BrowserContext.exposeFunction()
for context-wide exposed function.
NOTE: Functions installed via Page.exposeFunction()
survive navigations.
An example of adding a sha256
function to the page:
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({ headless: false });
Page page = browser.newPage();
page.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.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.click("button");
}
}
}
name
- Name of the function on the window objectcallback
- Callback function which will be called in Playwright's context.default void fill(String selector, String value)
selector
, waits for actionability checks, focuses the element, fills it and
triggers an input
event after filling. Note that you can pass an empty string to clear the input field.
If the target element is not an <input>
, <textarea>
or [contenteditable]
element, this method throws an error.
However, if the element is inside the <label>
element that has an associated control, the control will be filled
instead.
To send fine-grained keyboard events, use Page.type()
.
Shortcut for main frame's Frame.fill()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.value
- Value to fill for the <input>
, <textarea>
or [contenteditable]
element.void fill(String selector, String value, Page.FillOptions options)
selector
, waits for actionability checks, focuses the element, fills it and
triggers an input
event after filling. Note that you can pass an empty string to clear the input field.
If the target element is not an <input>
, <textarea>
or [contenteditable]
element, this method throws an error.
However, if the element is inside the <label>
element that has an associated control, the control will be filled
instead.
To send fine-grained keyboard events, use Page.type()
.
Shortcut for main frame's Frame.fill()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.value
- Value to fill for the <input>
, <textarea>
or [contenteditable]
element.default void focus(String selector)
selector
and focuses it. If there's no element matching selector
, the method
waits until a matching element appears in the DOM.
Shortcut for main frame's Frame.focus()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void focus(String selector, Page.FocusOptions options)
selector
and focuses it. If there's no element matching selector
, the method
waits until a matching element appears in the DOM.
Shortcut for main frame's Frame.focus()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.Frame frame(String name)
name
or url
must be specified.
Frame frame = page.frame("frame-name");
Frame frame = page.frameByUrl(Pattern.compile(".*domain.*");
name
- Frame name specified in the iframe
's name
attribute.Frame frameByUrl(String url)
url
- A glob pattern, regex pattern or predicate receiving frame's url
as a [URL] object.Frame frameByUrl(Pattern url)
url
- A glob pattern, regex pattern or predicate receiving frame's url
as a [URL] object.Frame frameByUrl(Predicate<String> url)
url
- A glob pattern, regex pattern or predicate receiving frame's url
as a [URL] object.default String getAttribute(String selector, String name)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.name
- Attribute name to get the value for.String getAttribute(String selector, String name, Page.GetAttributeOptions options)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.name
- Attribute name to get the value for.default Response goBack()
null
.
Navigate to the previous page in history.
Response goBack(Page.GoBackOptions options)
null
.
Navigate to the previous page in history.
default Response goForward()
null
.
Navigate to the next page in history.
Response goForward(Page.GoForwardOptions options)
null
.
Navigate to the next page in history.
default Response navigate(String url)
page.goto
will throw an error if:
timeout
is exceeded during navigation. page.goto
will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not
Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling Response.status()
.
NOTE: page.goto
either throws an error or returns a main resource response. The only exceptions are navigation to
about:blank
or navigation to the same URL with a different hash, which would succeed and return null
.
NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.
Shortcut for main frame's Frame.goto()
url
- URL to navigate page to. The url should include scheme, e.g. https://
.Response navigate(String url, Page.NavigateOptions options)
page.goto
will throw an error if:
timeout
is exceeded during navigation. page.goto
will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not
Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling Response.status()
.
NOTE: page.goto
either throws an error or returns a main resource response. The only exceptions are navigation to
about:blank
or navigation to the same URL with a different hash, which would succeed and return null
.
NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.
Shortcut for main frame's Frame.goto()
url
- URL to navigate page to. The url should include scheme, e.g. https://
.default void hover(String selector)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to hover over the center of the element, or the specified position
.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.hover()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void hover(String selector, Page.HoverOptions options)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to hover over the center of the element, or the specified position
.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.hover()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default String innerHTML(String selector)
element.innerHTML
.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.String innerHTML(String selector, Page.InnerHTMLOptions options)
element.innerHTML
.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default String innerText(String selector)
element.innerText
.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.String innerText(String selector, Page.InnerTextOptions options)
element.innerText
.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default boolean isChecked(String selector)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isChecked(String selector, Page.IsCheckedOptions options)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isClosed()
default boolean isDisabled(String selector)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isDisabled(String selector, Page.IsDisabledOptions options)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default boolean isEditable(String selector)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isEditable(String selector, Page.IsEditableOptions options)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default boolean isEnabled(String selector)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isEnabled(String selector, Page.IsEnabledOptions options)
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default boolean isHidden(String selector)
selector
that does not match any elements
is considered hidden.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isHidden(String selector, Page.IsHiddenOptions options)
selector
that does not match any elements
is considered hidden.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default boolean isVisible(String selector)
selector
that does not match any elements is considered not visible.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.boolean isVisible(String selector, Page.IsVisibleOptions options)
selector
that does not match any elements is considered not visible.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.Keyboard keyboard()
Frame mainFrame()
Mouse mouse()
Page opener()
null
for others. If the opener has been closed already the returns null
.void pause()
playwright.resume()
in the DevTools console.
User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.
NOTE: This method requires Playwright to be started in a headed mode, with a falsy headless
value in the BrowserType.launch()
.
default byte[] pdf()
NOTE: Generating a pdf is currently only supported in Chromium headless.
page.pdf()
generates a pdf of the page with print
css media. To generate a pdf with screen
media, call Page.emulateMedia()
before calling page.pdf()
:
NOTE: By default, page.pdf()
generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust
property to force rendering of exact colors.
// Generates a PDF with "screen" media type.
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN));
page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));
The width
, height
, and margin
options accept values labeled with units. Unlabeled values are treated as pixels.
A few examples:
page.pdf({width: 100})
- prints with width set to 100 pixelspage.pdf({width: '100px'})
- prints with width set to 100 pixelspage.pdf({width: '10cm'})
- prints with width set to 10 centimeters.All possible units are:
px
- pixelin
- inchcm
- centimetermm
- millimeter The format
options are:
Letter
: 8.5in x 11inLegal
: 8.5in x 14inTabloid
: 11in x 17inLedger
: 17in x 11inA0
: 33.1in x 46.8inA1
: 23.4in x 33.1inA2
: 16.54in x 23.4inA3
: 11.7in x 16.54inA4
: 8.27in x 11.7inA5
: 5.83in x 8.27inA6
: 4.13in x 5.83in NOTE: headerTemplate
and footerTemplate
markup have the following limitations: > 1. Script tags inside templates are not
evaluated. > 2. Page styles are not visible inside templates.
byte[] pdf(Page.PdfOptions options)
NOTE: Generating a pdf is currently only supported in Chromium headless.
page.pdf()
generates a pdf of the page with print
css media. To generate a pdf with screen
media, call Page.emulateMedia()
before calling page.pdf()
:
NOTE: By default, page.pdf()
generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust
property to force rendering of exact colors.
// Generates a PDF with "screen" media type.
page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN));
page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));
The width
, height
, and margin
options accept values labeled with units. Unlabeled values are treated as pixels.
A few examples:
page.pdf({width: 100})
- prints with width set to 100 pixelspage.pdf({width: '100px'})
- prints with width set to 100 pixelspage.pdf({width: '10cm'})
- prints with width set to 10 centimeters.All possible units are:
px
- pixelin
- inchcm
- centimetermm
- millimeter The format
options are:
Letter
: 8.5in x 11inLegal
: 8.5in x 14inTabloid
: 11in x 17inLedger
: 17in x 11inA0
: 33.1in x 46.8inA1
: 23.4in x 33.1inA2
: 16.54in x 23.4inA3
: 11.7in x 16.54inA4
: 8.27in x 11.7inA5
: 5.83in x 8.27inA6
: 4.13in x 5.83in NOTE: headerTemplate
and footerTemplate
markup have the following limitations: > 1. Script tags inside templates are not
evaluated. > 2. Page styles are not visible inside templates.
default void press(String selector, String key)
Keyboard.down()
and Keyboard.up()
.
key
can specify the intended keyboardEvent.key value or a single
character to generate the text for. A superset of the key
values can be found here. Examples of the keys are:
F1
- F12
, Digit0
- Digit9
, KeyA
- KeyZ
, Backquote
, Minus
, Equal
, Backslash
, Backspace
, Tab
,
Delete
, Escape
, ArrowDown
, End
, Enter
, Home
, Insert
, PageDown
, PageUp
, ArrowRight
, ArrowUp
, etc.
Following modification shortcuts are also supported: Shift
, Control
, Alt
, Meta
, ShiftLeft
.
Holding down Shift
will type the text that corresponds to the key
in the upper case.
If key
is a single character, it is case-sensitive, so the values a
and A
will generate different respective
texts.
Shortcuts such as key: "Control+o"
or key: "Control+Shift+T"
are supported as well. When specified with the
modifier, modifier is pressed and being held while the subsequent key is being pressed.
Page page = browser.newPage();
page.navigate("https://keycode.info");
page.press("body", "A");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png")));
page.press("body", "ArrowLeft");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" )));
page.press("body", "Shift+O");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" )));
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.key
- Name of the key to press or a character to generate, such as ArrowLeft
or a
.void press(String selector, String key, Page.PressOptions options)
Keyboard.down()
and Keyboard.up()
.
key
can specify the intended keyboardEvent.key value or a single
character to generate the text for. A superset of the key
values can be found here. Examples of the keys are:
F1
- F12
, Digit0
- Digit9
, KeyA
- KeyZ
, Backquote
, Minus
, Equal
, Backslash
, Backspace
, Tab
,
Delete
, Escape
, ArrowDown
, End
, Enter
, Home
, Insert
, PageDown
, PageUp
, ArrowRight
, ArrowUp
, etc.
Following modification shortcuts are also supported: Shift
, Control
, Alt
, Meta
, ShiftLeft
.
Holding down Shift
will type the text that corresponds to the key
in the upper case.
If key
is a single character, it is case-sensitive, so the values a
and A
will generate different respective
texts.
Shortcuts such as key: "Control+o"
or key: "Control+Shift+T"
are supported as well. When specified with the
modifier, modifier is pressed and being held while the subsequent key is being pressed.
Page page = browser.newPage();
page.navigate("https://keycode.info");
page.press("body", "A");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png")));
page.press("body", "ArrowLeft");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" )));
page.press("body", "Shift+O");
page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" )));
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.key
- Name of the key to press or a character to generate, such as ArrowLeft
or a
.ElementHandle querySelector(String selector)
null
. To wait for an element on the page, use Page.waitForSelector()
.
Shortcut for main frame's Frame.querySelector()
.
selector
- A selector to query for. See working with selectors for more
details.List<ElementHandle> querySelectorAll(String selector)
[]
.
Shortcut for main frame's Frame.querySelectorAll()
.
selector
- A selector to query for. See working with selectors for more
details.default Response reload()
Response reload(Page.ReloadOptions options)
void route(String url, Consumer<Route> handler)
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
An example of a naive handler that aborts all image requests:
Page page = browser.newPage();
page.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
page.navigate("https://example.com");
browser.close();
or the same snippet using a regex pattern instead:
Page page = browser.newPage();
page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
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:
page.route("/api/**", route -> {
if (route.request().postData().contains("my-string"))
route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
else
route.resume();
});
Page routes take precedence over browser context routes (set up with BrowserContext.route()
) when request matches both handlers.
To remove a route with its handler you can use Page.unroute()
.
NOTE: Enabling routing disables http cache.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler
- handler function to route the request.void route(Pattern url, Consumer<Route> handler)
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
An example of a naive handler that aborts all image requests:
Page page = browser.newPage();
page.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
page.navigate("https://example.com");
browser.close();
or the same snippet using a regex pattern instead:
Page page = browser.newPage();
page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
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:
page.route("/api/**", route -> {
if (route.request().postData().contains("my-string"))
route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
else
route.resume();
});
Page routes take precedence over browser context routes (set up with BrowserContext.route()
) when request matches both handlers.
To remove a route with its handler you can use Page.unroute()
.
NOTE: Enabling routing disables http cache.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler
- handler function to route the request.void route(Predicate<String> url, Consumer<Route> handler)
Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
An example of a naive handler that aborts all image requests:
Page page = browser.newPage();
page.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
page.navigate("https://example.com");
browser.close();
or the same snippet using a regex pattern instead:
Page page = browser.newPage();
page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
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:
page.route("/api/**", route -> {
if (route.request().postData().contains("my-string"))
route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
else
route.resume();
});
Page routes take precedence over browser context routes (set up with BrowserContext.route()
) when request matches both handlers.
To remove a route with its handler you can use Page.unroute()
.
NOTE: Enabling routing disables http cache.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler
- handler function to route the request.default byte[] screenshot()
byte[] screenshot(Page.ScreenshotOptions options)
default List<String> selectOption(String selector, String values)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.List<String> selectOption(String selector, String values, Page.SelectOptionOptions options)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.default List<String> selectOption(String selector, ElementHandle values)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.List<String> selectOption(String selector, ElementHandle values, Page.SelectOptionOptions options)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.default List<String> selectOption(String selector, String[] values)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.List<String> selectOption(String selector, String[] values, Page.SelectOptionOptions options)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.default List<String> selectOption(String selector, SelectOption values)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.List<String> selectOption(String selector, SelectOption values, Page.SelectOptionOptions options)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.default List<String> selectOption(String selector, ElementHandle[] values)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.List<String> selectOption(String selector, ElementHandle[] values, Page.SelectOptionOptions options)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.default List<String> selectOption(String selector, SelectOption[] values)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.List<String> selectOption(String selector, SelectOption[] values, Page.SelectOptionOptions options)
selector
, waits for actionability checks, waits until all specified options are
present in the <select>
element and selects these options.
If the target element is not a <select>
element, this method throws an error. However, if the element is inside the
<label>
element that has an associated control, the control will be used
instead.
Returns the array of option values that have been successfully selected.
Triggers a change
and input
event once all the provided options have been selected.
// single selection matching the value
page.selectOption("select#colors", "blue");
// single selection matching both the value and the label
page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
// multiple selection
page.selectOption("select#colors", new String[] {"red", "green", "blue"});
Shortcut for main frame's Frame.selectOption()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.values
- Options to select. If the <select>
has the multiple
attribute, all matching options are selected, otherwise only the
first option matching one of the passed options is selected. String values are equivalent to {value:'string'}
. Option
is considered matching if all specified properties match.default void setContent(String html)
html
- HTML markup to assign to the page.void setContent(String html, Page.SetContentOptions options)
html
- HTML markup to assign to the page.void setDefaultNavigationTimeout(double timeout)
Page.goBack()
Page.goForward()
Page.goto()
Page.reload()
Page.setContent()
Page.waitForNavigation()
Page.waitForURL()
NOTE: Page.setDefaultNavigationTimeout()
takes priority over Page.setDefaultTimeout()
, BrowserContext.setDefaultTimeout()
and BrowserContext.setDefaultNavigationTimeout()
.
timeout
- Maximum navigation time in millisecondsvoid setDefaultTimeout(double timeout)
timeout
option.
NOTE: Page.setDefaultNavigationTimeout()
takes priority over Page.setDefaultTimeout()
.
timeout
- Maximum time in millisecondsvoid setExtraHTTPHeaders(Map<String,String> headers)
NOTE: Page.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.default void setInputFiles(String selector, Path files)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void setInputFiles(String selector, Path files, Page.SetInputFilesOptions options)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void setInputFiles(String selector, Path[] files)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void setInputFiles(String selector, Path[] files, Page.SetInputFilesOptions options)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void setInputFiles(String selector, FilePayload files)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void setInputFiles(String selector, FilePayload files, Page.SetInputFilesOptions options)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void setInputFiles(String selector, FilePayload[] files)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void setInputFiles(String selector, FilePayload[] files, Page.SetInputFilesOptions options)
selector
to point to an input element.
Sets the value of the file input to these file paths or files. If some of the filePaths
are relative paths, then they
are resolved relative to the the current working directory. For empty array, clears the selected files.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void setViewportSize(int width, int height)
Browser.newContext()
allows to set viewport size (and more) for all pages in the context at once.
page.setViewportSize
will resize the page. A lot of websites don't expect phones to change size, so you should set the
viewport size before navigating to the page.
Page page = browser.newPage();
page.setViewportSize(640, 480);
page.navigate("https://example.com");
default void tap(String selector)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.touchscreen()
to tap the center of the element, or the specified position
.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
NOTE: Page.tap()
requires that the hasTouch
option of the browser context be set to true.
Shortcut for main frame's Frame.tap()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void tap(String selector, Page.TapOptions options)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.touchscreen()
to tap the center of the element, or the specified position
.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
NOTE: Page.tap()
requires that the hasTouch
option of the browser context be set to true.
Shortcut for main frame's Frame.tap()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default String textContent(String selector)
element.textContent
.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.String textContent(String selector, Page.TextContentOptions options)
element.textContent
.selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.String title()
Frame.title()
.Touchscreen touchscreen()
default void type(String selector, String text)
keydown
, keypress
/input
, and keyup
event for each character in the text. page.type
can be used to send
fine-grained keyboard events. To fill values in form fields, use Page.fill()
.
To press a special key, like Control
or ArrowDown
, use Keyboard.press()
.
// Types instantly
page.type("#mytextarea", "Hello");
// Types slower, like a user
page.type("#mytextarea", "World", new Page.TypeOptions().setDelay(100));
Shortcut for main frame's Frame.type()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.text
- A text to type into a focused element.void type(String selector, String text, Page.TypeOptions options)
keydown
, keypress
/input
, and keyup
event for each character in the text. page.type
can be used to send
fine-grained keyboard events. To fill values in form fields, use Page.fill()
.
To press a special key, like Control
or ArrowDown
, use Keyboard.press()
.
// Types instantly
page.type("#mytextarea", "Hello");
// Types slower, like a user
page.type("#mytextarea", "World", new Page.TypeOptions().setDelay(100));
Shortcut for main frame's Frame.type()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.text
- A text to type into a focused element.default void uncheck(String selector)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to click in the center of the element.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.uncheck()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.void uncheck(String selector, Page.UncheckOptions options)
selector
by performing the following steps:
selector
. If there is none, wait until a matching element is attached to the DOM.force
option is set. If the element is detached during the checks, the whole action is retried.Page.mouse()
to click in the center of the element.noWaitAfter
option is set. When all steps combined have not finished during the specified timeout
, this method throws a TimeoutError
. Passing
zero timeout disables this.
Shortcut for main frame's Frame.uncheck()
.
selector
- A selector to search for element. If there are multiple elements satisfying the selector, the first will be used. See working with selectors for more details.default void unroute(String url)
Page.route()
. When handler
is not specified, removes all routes for
the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.void unroute(String url, Consumer<Route> handler)
Page.route()
. When handler
is not specified, removes all routes for
the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler
- Optional handler function to route the request.default void unroute(Pattern url)
Page.route()
. When handler
is not specified, removes all routes for
the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.void unroute(Pattern url, Consumer<Route> handler)
Page.route()
. When handler
is not specified, removes all routes for
the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler
- Optional handler function to route the request.default void unroute(Predicate<String> url)
Page.route()
. When handler
is not specified, removes all routes for
the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.void unroute(Predicate<String> url, Consumer<Route> handler)
Page.route()
. When handler
is not specified, removes all routes for
the url
.url
- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler
- Optional handler function to route the request.String url()
Frame.url()
.Video video()
ViewportSize viewportSize()
default Page waitForClose(Runnable callback)
callback
- Callback that performs the action triggering the event.Page waitForClose(Page.WaitForCloseOptions options, Runnable callback)
callback
- Callback that performs the action triggering the event.default ConsoleMessage waitForConsoleMessage(Runnable callback)
ConsoleMessage
to be logged by in the page. 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 Page.onConsole()
event is fired.callback
- Callback that performs the action triggering the event.ConsoleMessage waitForConsoleMessage(Page.WaitForConsoleMessageOptions options, Runnable callback)
ConsoleMessage
to be logged by in the page. 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 Page.onConsole()
event is fired.callback
- Callback that performs the action triggering the event.default Download waitForDownload(Runnable callback)
Download
. If predicate is provided, it passes Download
value into the
predicate
function and waits for predicate(download)
to return a truthy value. Will throw an error if the page is
closed before the download event is fired.callback
- Callback that performs the action triggering the event.Download waitForDownload(Page.WaitForDownloadOptions options, Runnable callback)
Download
. If predicate is provided, it passes Download
value into the
predicate
function and waits for predicate(download)
to return a truthy value. Will throw an error if the page is
closed before the download event is fired.callback
- Callback that performs the action triggering the event.default FileChooser waitForFileChooser(Runnable callback)
FileChooser
to be created. If predicate is provided, it passes FileChooser
value
into the predicate
function and waits for predicate(fileChooser)
to return a truthy value. Will throw an error if
the page is closed before the file chooser is opened.callback
- Callback that performs the action triggering the event.FileChooser waitForFileChooser(Page.WaitForFileChooserOptions options, Runnable callback)
FileChooser
to be created. If predicate is provided, it passes FileChooser
value
into the predicate
function and waits for predicate(fileChooser)
to return a truthy value. Will throw an error if
the page is closed before the file chooser is opened.callback
- Callback that performs the action triggering the event.default JSHandle waitForFunction(String expression, Object arg)
expression
returns a truthy value. It resolves to a JSHandle of the truthy value.
The Page.waitForFunction()
can be used to observe viewport size change:
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();
Page page = browser.newPage();
page.setViewportSize(50, 50);
page.waitForFunction("() => window.innerWidth < 100");
browser.close();
}
}
}
To pass an argument to the predicate of Page.waitForFunction()
function:
String selector = ".foo";
page.waitForFunction("selector => !!document.querySelector(selector)", selector);
Shortcut for main frame's Frame.waitForFunction()
.
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.arg
- Optional argument to pass to expression
.default JSHandle waitForFunction(String expression)
expression
returns a truthy value. It resolves to a JSHandle of the truthy value.
The Page.waitForFunction()
can be used to observe viewport size change:
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();
Page page = browser.newPage();
page.setViewportSize(50, 50);
page.waitForFunction("() => window.innerWidth < 100");
browser.close();
}
}
}
To pass an argument to the predicate of Page.waitForFunction()
function:
String selector = ".foo";
page.waitForFunction("selector => !!document.querySelector(selector)", selector);
Shortcut for main frame's Frame.waitForFunction()
.
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.JSHandle waitForFunction(String expression, Object arg, Page.WaitForFunctionOptions options)
expression
returns a truthy value. It resolves to a JSHandle of the truthy value.
The Page.waitForFunction()
can be used to observe viewport size change:
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();
Page page = browser.newPage();
page.setViewportSize(50, 50);
page.waitForFunction("() => window.innerWidth < 100");
browser.close();
}
}
}
To pass an argument to the predicate of Page.waitForFunction()
function:
String selector = ".foo";
page.waitForFunction("selector => !!document.querySelector(selector)", selector);
Shortcut for main frame's Frame.waitForFunction()
.
expression
- JavaScript expression to be evaluated in the browser context. If it looks like a function declaration, it is interpreted
as a function. Otherwise, evaluated as an expression.arg
- Optional argument to pass to expression
.default void waitForLoadState(LoadState state)
This resolves when the page reaches a required load state, load
by default. The navigation must have been committed
when this method is called. If current document has already reached the required state, resolves immediately.
page.click("button"); // Click triggers navigation.
page.waitForLoadState(); // The promise resolves after "load" event.
Page popup = page.waitForPopup(() -> {
page.click("button"); // Click triggers a popup.
});
popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
System.out.println(popup.title()); // Popup is ready to use.
Shortcut for main frame's Frame.waitForLoadState()
.
state
- Optional load state to wait for, defaults to load
. If the state has been already reached while loading current
document, the method resolves immediately. Can be one of:
"load"
- wait for the load
event to be fired."domcontentloaded"
- wait for the DOMContentLoaded
event to be fired."networkidle"
- wait until there are no network connections for at least 500
ms.default void waitForLoadState()
This resolves when the page reaches a required load state, load
by default. The navigation must have been committed
when this method is called. If current document has already reached the required state, resolves immediately.
page.click("button"); // Click triggers navigation.
page.waitForLoadState(); // The promise resolves after "load" event.
Page popup = page.waitForPopup(() -> {
page.click("button"); // Click triggers a popup.
});
popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
System.out.println(popup.title()); // Popup is ready to use.
Shortcut for main frame's Frame.waitForLoadState()
.
void waitForLoadState(LoadState state, Page.WaitForLoadStateOptions options)
This resolves when the page reaches a required load state, load
by default. The navigation must have been committed
when this method is called. If current document has already reached the required state, resolves immediately.
page.click("button"); // Click triggers navigation.
page.waitForLoadState(); // The promise resolves after "load" event.
Page popup = page.waitForPopup(() -> {
page.click("button"); // Click triggers a popup.
});
popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
System.out.println(popup.title()); // Popup is ready to use.
Shortcut for main frame's Frame.waitForLoadState()
.
state
- Optional load state to wait for, defaults to load
. If the state has been already reached while loading current
document, the method resolves immediately. Can be one of:
"load"
- wait for the load
event to be fired."domcontentloaded"
- wait for the DOMContentLoaded
event to be fired."networkidle"
- wait until there are no network connections for at least 500
ms.default Response waitForNavigation(Runnable callback)
null
.
This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly
cause the page to navigate. e.g. The click target has an onclick
handler that triggers navigation from a setTimeout
.
Consider this example:
// The method returns after navigation has finished
Response response = page.waitForNavigation(() -> {
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
});
NOTE: Usage of the History API to change the URL is considered a navigation.
Shortcut for main frame's Frame.waitForNavigation()
.
callback
- Callback that performs the action triggering the event.Response waitForNavigation(Page.WaitForNavigationOptions options, Runnable callback)
null
.
This resolves when the page navigates to a new URL or reloads. It is useful for when you run code which will indirectly
cause the page to navigate. e.g. The click target has an onclick
handler that triggers navigation from a setTimeout
.
Consider this example:
// The method returns after navigation has finished
Response response = page.waitForNavigation(() -> {
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
});
NOTE: Usage of the History API to change the URL is considered a navigation.
Shortcut for main frame's Frame.waitForNavigation()
.
callback
- Callback that performs the action triggering the event.default Page waitForPopup(Runnable callback)
Page
. If predicate is provided, it passes [Popup] value into the predicate
function and waits for predicate(page)
to return a truthy value. Will throw an error if the page is closed before the
popup event is fired.callback
- Callback that performs the action triggering the event.Page waitForPopup(Page.WaitForPopupOptions options, Runnable callback)
Page
. If predicate is provided, it passes [Popup] value into the predicate
function and waits for predicate(page)
to return a truthy value. Will throw an error if the page is closed before the
popup event is fired.callback
- Callback that performs the action triggering the event.default Request waitForRequest(String urlOrPredicate, Runnable callback)
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.click("button.triggers-request");
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.click("button.triggers-request");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Request
object.callback
- Callback that performs the action triggering the event.Request waitForRequest(String urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.click("button.triggers-request");
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.click("button.triggers-request");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Request
object.callback
- Callback that performs the action triggering the event.default Request waitForRequest(Pattern urlOrPredicate, Runnable callback)
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.click("button.triggers-request");
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.click("button.triggers-request");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Request
object.callback
- Callback that performs the action triggering the event.Request waitForRequest(Pattern urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.click("button.triggers-request");
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.click("button.triggers-request");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Request
object.callback
- Callback that performs the action triggering the event.default Request waitForRequest(Predicate<Request> urlOrPredicate, Runnable callback)
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.click("button.triggers-request");
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.click("button.triggers-request");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Request
object.callback
- Callback that performs the action triggering the event.Request waitForRequest(Predicate<Request> urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)
// Waits for the next request with the specified url
Request request = page.waitForRequest("https://example.com/resource", () -> {
// Triggers the request
page.click("button.triggers-request");
});
// Waits for the next request matching some conditions
Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
// Triggers the request
page.click("button.triggers-request");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Request
object.callback
- Callback that performs the action triggering the event.default Request waitForRequestFinished(Runnable callback)
Request
to finish loading. If predicate is provided, it passes Request
value into
the predicate
function and waits for predicate(request)
to return a truthy value. Will throw an error if the page is
closed before the Page.onRequestFinished()
event is fired.callback
- Callback that performs the action triggering the event.Request waitForRequestFinished(Page.WaitForRequestFinishedOptions options, Runnable callback)
Request
to finish loading. If predicate is provided, it passes Request
value into
the predicate
function and waits for predicate(request)
to return a truthy value. Will throw an error if the page is
closed before the Page.onRequestFinished()
event is fired.callback
- Callback that performs the action triggering the event.default Response waitForResponse(String urlOrPredicate, Runnable callback)
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.click("button.triggers-response");
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response
page.click("button.triggers-response");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Response
object.callback
- Callback that performs the action triggering the event.Response waitForResponse(String urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.click("button.triggers-response");
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response
page.click("button.triggers-response");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Response
object.callback
- Callback that performs the action triggering the event.default Response waitForResponse(Pattern urlOrPredicate, Runnable callback)
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.click("button.triggers-response");
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response
page.click("button.triggers-response");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Response
object.callback
- Callback that performs the action triggering the event.Response waitForResponse(Pattern urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.click("button.triggers-response");
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response
page.click("button.triggers-response");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Response
object.callback
- Callback that performs the action triggering the event.default Response waitForResponse(Predicate<Response> urlOrPredicate, Runnable callback)
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.click("button.triggers-response");
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response
page.click("button.triggers-response");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Response
object.callback
- Callback that performs the action triggering the event.Response waitForResponse(Predicate<Response> urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)
// Waits for the next response with the specified url
Response response = page.waitForResponse("https://example.com/resource", () -> {
// Triggers the response
page.click("button.triggers-response");
});
// Waits for the next response matching some conditions
Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
// Triggers the response
page.click("button.triggers-response");
});
urlOrPredicate
- Request URL string, regex or predicate receiving Response
object.callback
- Callback that performs the action triggering the event.default ElementHandle waitForSelector(String selector)
state
option. Returns null
if waiting for hidden
or
detached
.
Wait for the selector
to satisfy state
option (either appear/disappear from dom, or become visible/hidden). If at
the moment of calling the method selector
already satisfies the condition, the method will return immediately. If the
selector doesn't satisfy the condition for the timeout
milliseconds, the function will throw.
This method works across navigations:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch();
Page page = browser.newPage();
for (String currentURL : Arrays.asList("https://google.com", "https://bbc.com")) {
page.navigate(currentURL);
ElementHandle element = page.waitForSelector("img");
System.out.println("Loaded image: " + element.getAttribute("src"));
}
browser.close();
}
}
}
selector
- A selector to query for. See working with selectors for more
details.ElementHandle waitForSelector(String selector, Page.WaitForSelectorOptions options)
state
option. Returns null
if waiting for hidden
or
detached
.
Wait for the selector
to satisfy state
option (either appear/disappear from dom, or become visible/hidden). If at
the moment of calling the method selector
already satisfies the condition, the method will return immediately. If the
selector doesn't satisfy the condition for the timeout
milliseconds, the function will throw.
This method works across navigations:
import com.microsoft.playwright.*;
public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
Browser browser = chromium.launch();
Page page = browser.newPage();
for (String currentURL : Arrays.asList("https://google.com", "https://bbc.com")) {
page.navigate(currentURL);
ElementHandle element = page.waitForSelector("img");
System.out.println("Loaded image: " + element.getAttribute("src"));
}
browser.close();
}
}
}
selector
- A selector to query for. See working with selectors for more
details.void waitForTimeout(double timeout)
timeout
in milliseconds.
Note that page.waitForTimeout()
should only be used for debugging. Tests using the timer in production are going to be
flaky. Use signals such as network events, selectors becoming visible and others instead.
// wait for 1 second
page.waitForTimeout(1000);
Shortcut for main frame's Frame.waitForTimeout()
.
timeout
- A timeout to wait fordefault void waitForURL(String url)
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**\/target.html");
Shortcut for main frame's Frame.waitForURL()
.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.void waitForURL(String url, Page.WaitForURLOptions options)
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**\/target.html");
Shortcut for main frame's Frame.waitForURL()
.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.default void waitForURL(Pattern url)
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**\/target.html");
Shortcut for main frame's Frame.waitForURL()
.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.void waitForURL(Pattern url, Page.WaitForURLOptions options)
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**\/target.html");
Shortcut for main frame's Frame.waitForURL()
.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.default void waitForURL(Predicate<String> url)
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**\/target.html");
Shortcut for main frame's Frame.waitForURL()
.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.void waitForURL(Predicate<String> url, Page.WaitForURLOptions options)
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
page.waitForURL("**\/target.html");
Shortcut for main frame's Frame.waitForURL()
.
url
- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation.default WebSocket waitForWebSocket(Runnable callback)
WebSocket
. If predicate is provided, it passes WebSocket
value into the
predicate
function and waits for predicate(webSocket)
to return a truthy value. Will throw an error if the page is
closed before the WebSocket event is fired.callback
- Callback that performs the action triggering the event.WebSocket waitForWebSocket(Page.WaitForWebSocketOptions options, Runnable callback)
WebSocket
. If predicate is provided, it passes WebSocket
value into the
predicate
function and waits for predicate(webSocket)
to return a truthy value. Will throw an error if the page is
closed before the WebSocket event is fired.callback
- Callback that performs the action triggering the event.default Worker waitForWorker(Runnable callback)
Worker
. If predicate is provided, it passes Worker
value into the predicate
function and waits for predicate(worker)
to return a truthy value. Will throw an error if the page is closed before
the worker event is fired.callback
- Callback that performs the action triggering the event.Worker waitForWorker(Page.WaitForWorkerOptions options, Runnable callback)
Worker
. If predicate is provided, it passes Worker
value into the predicate
function and waits for predicate(worker)
to return a truthy value. Will throw an error if the page is closed before
the worker event is fired.callback
- Callback that performs the action triggering the event.List<Worker> workers()
NOTE: This does not contain ServiceWorkers
void onceDialog(Consumer<Dialog> handler)
Dialog
handler. The handler will be removed immediately after next Dialog
is created.
page.onceDialog(dialog -> {
dialog.accept("foo");
});
// prints 'foo'
System.out.println(page.evaluate("prompt('Enter string:')"));
// prints 'null' as the dialog will be auto-dismissed because there are no handlers.
System.out.println(page.evaluate("prompt('Enter string:')"));
This code above is equivalent to:
{@code Consumer
handler
- Receives the Dialog
object, it **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.Copyright © 2021. All rights reserved.