Interface Page
- All Superinterfaces:
AutoCloseable
- All Known Implementing Classes:
PageImpl
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);
-
Nested Class Summary
Nested ClassesModifier and TypeInterfaceDescriptionstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic classstatic class -
Method Summary
Modifier and TypeMethodDescriptionvoidaddInitScript(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.voidaddInitScript(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.default ElementHandleAdds a<script>tag into the page with the desired url or content.addScriptTag(Page.AddScriptTagOptions options) Adds a<script>tag into the page with the desired url or content.default ElementHandleAdds a<link rel="stylesheet">tag into the page with the desired url or a<style type="text/css">tag with the content.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.voidBrings page to front (activates tab).default voidThis method checks an element matchingselectorby performing the following steps: Find an element matchingselector.voidcheck(String selector, Page.CheckOptions options) This method checks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidThis method clicks an element matchingselectorby performing the following steps: Find an element matchingselector.voidclick(String selector, Page.ClickOptions options) This method clicks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidclose()IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed.voidclose(Page.CloseOptions options) IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed.content()Gets the full HTML contents of the page, including the doctype.context()Get the browser context that the page belongs to.default voidThis method double clicks an element matchingselectorby performing the following steps: Find an element matchingselector.voiddblclick(String selector, Page.DblclickOptions options) This method double clicks an element matchingselectorby performing the following steps: Find an element matchingselector.default voiddispatchEvent(String selector, String type) The snippet below dispatches theclickevent on the element.default voiddispatchEvent(String selector, String type, Object eventInit) The snippet below dispatches theclickevent on the element.voiddispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options) The snippet below dispatches theclickevent on the element.default voiddragAndDrop(String source, String target) This method drags the source element to the target element.voiddragAndDrop(String source, String target, Page.DragAndDropOptions options) This method drags the source element to the target element.default voidThis method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.voidemulateMedia(Page.EmulateMediaOptions options) This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.default ObjectevalOnSelector(String selector, String expression) The method finds an element matching the specified selector within the page and passes it as a first argument toexpression.default ObjectevalOnSelector(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 toexpression.evalOnSelector(String selector, String expression, Object arg, Page.EvalOnSelectorOptions options) The method finds an element matching the specified selector within the page and passes it as a first argument toexpression.default ObjectevalOnSelectorAll(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 toexpression.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 toexpression.default ObjectReturns the value of theexpressioninvocation.Returns the value of theexpressioninvocation.default JSHandleevaluateHandle(String expression) Returns the value of theexpressioninvocation as aJSHandle.evaluateHandle(String expression, Object arg) Returns the value of theexpressioninvocation as aJSHandle.default voidexposeBinding(String name, BindingCallback callback) The method adds a function callednameon thewindowobject of every frame in this page.voidexposeBinding(String name, BindingCallback callback, Page.ExposeBindingOptions options) The method adds a function callednameon thewindowobject of every frame in this page.voidexposeFunction(String name, FunctionCallback callback) The method adds a function callednameon thewindowobject of every frame in the page.default voidThis method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent after filling.voidfill(String selector, String value, Page.FillOptions options) This method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent after filling.default voidThis method fetches an element withselectorand focuses it.voidfocus(String selector, Page.FocusOptions options) This method fetches an element withselectorand focuses it.Returns frame matching the specified criteria.frameByUrl(String url) Returns frame with matching URL.frameByUrl(Predicate<String> url) Returns frame with matching URL.frameByUrl(Pattern url) Returns frame with matching URL.frameLocator(String selector) When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.frames()An array of all frames attached to the page.default StringgetAttribute(String selector, String name) Returns element attribute value.getAttribute(String selector, String name, Page.GetAttributeOptions options) Returns element attribute value.default LocatorgetByAltText(String text) Allows locating elements by their alt text.getByAltText(String text, Page.GetByAltTextOptions options) Allows locating elements by their alt text.default LocatorgetByAltText(Pattern text) Allows locating elements by their alt text.getByAltText(Pattern text, Page.GetByAltTextOptions options) Allows locating elements by their alt text.default LocatorgetByLabel(String text) Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.getByLabel(String text, Page.GetByLabelOptions options) Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.default LocatorgetByLabel(Pattern text) Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.getByLabel(Pattern text, Page.GetByLabelOptions options) Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.default LocatorgetByPlaceholder(String text) Allows locating input elements by the placeholder text.getByPlaceholder(String text, Page.GetByPlaceholderOptions options) Allows locating input elements by the placeholder text.default LocatorgetByPlaceholder(Pattern text) Allows locating input elements by the placeholder text.getByPlaceholder(Pattern text, Page.GetByPlaceholderOptions options) Allows locating input elements by the placeholder text.default LocatorgetByRole(AriaRole role, Page.GetByRoleOptions options) getByTestId(String testId) Locate element by the test id.getByTestId(Pattern testId) Locate element by the test id.default LocatorAllows locating elements that contain given text.getByText(String text, Page.GetByTextOptions options) Allows locating elements that contain given text.default LocatorAllows locating elements that contain given text.getByText(Pattern text, Page.GetByTextOptions options) Allows locating elements that contain given text.default LocatorgetByTitle(String text) Allows locating elements by their title attribute.getByTitle(String text, Page.GetByTitleOptions options) Allows locating elements by their title attribute.default LocatorgetByTitle(Pattern text) Allows locating elements by their title attribute.getByTitle(Pattern text, Page.GetByTitleOptions options) Allows locating elements by their title attribute.default ResponsegoBack()Returns the main resource response.goBack(Page.GoBackOptions options) Returns the main resource response.default ResponseReturns the main resource response.goForward(Page.GoForwardOptions options) Returns the main resource response.default voidThis method hovers over an element matchingselectorby performing the following steps: Find an element matchingselector.voidhover(String selector, Page.HoverOptions options) This method hovers over an element matchingselectorby performing the following steps: Find an element matchingselector.default StringReturnselement.innerHTML.innerHTML(String selector, Page.InnerHTMLOptions options) Returnselement.innerHTML.default StringReturnselement.innerText.innerText(String selector, Page.InnerTextOptions options) Returnselement.innerText.default StringinputValue(String selector) Returnsinput.valuefor the selected<input>or<textarea>or<select>element.inputValue(String selector, Page.InputValueOptions options) Returnsinput.valuefor the selected<input>or<textarea>or<select>element.default booleanReturns whether the element is checked.booleanisChecked(String selector, Page.IsCheckedOptions options) Returns whether the element is checked.booleanisClosed()Indicates that the page has been closed.default booleanisDisabled(String selector) Returns whether the element is disabled, the opposite of enabled.booleanisDisabled(String selector, Page.IsDisabledOptions options) Returns whether the element is disabled, the opposite of enabled.default booleanisEditable(String selector) Returns whether the element is editable.booleanisEditable(String selector, Page.IsEditableOptions options) Returns whether the element is editable.default booleanReturns whether the element is enabled.booleanisEnabled(String selector, Page.IsEnabledOptions options) Returns whether the element is enabled.default booleanReturns whether the element is hidden, the opposite of visible.booleanisHidden(String selector, Page.IsHiddenOptions options) Returns whether the element is hidden, the opposite of visible.default booleanReturns whether the element is visible.booleanisVisible(String selector, Page.IsVisibleOptions options) Returns whether the element is visible.keyboard()default LocatorThe method returns an element locator that can be used to perform actions on this page / frame.locator(String selector, Page.LocatorOptions options) The method returns an element locator that can be used to perform actions on this page / frame.The page's main frame.mouse()default ResponseReturns the main resource response.navigate(String url, Page.NavigateOptions options) Returns the main resource response.voidRemoves handler that was previously added withonClose(handler).voidoffConsoleMessage(Consumer<ConsoleMessage> handler) Removes handler that was previously added withonConsoleMessage(handler).voidRemoves handler that was previously added withonCrash(handler).voidRemoves handler that was previously added withonDialog(handler).voidoffDOMContentLoaded(Consumer<Page> handler) Removes handler that was previously added withonDOMContentLoaded(handler).voidoffDownload(Consumer<Download> handler) Removes handler that was previously added withonDownload(handler).voidoffFileChooser(Consumer<FileChooser> handler) Removes handler that was previously added withonFileChooser(handler).voidoffFrameAttached(Consumer<Frame> handler) Removes handler that was previously added withonFrameAttached(handler).voidoffFrameDetached(Consumer<Frame> handler) Removes handler that was previously added withonFrameDetached(handler).voidoffFrameNavigated(Consumer<Frame> handler) Removes handler that was previously added withonFrameNavigated(handler).voidRemoves handler that was previously added withonLoad(handler).voidoffPageError(Consumer<String> handler) Removes handler that was previously added withonPageError(handler).voidRemoves handler that was previously added withonPopup(handler).voidoffRequest(Consumer<Request> handler) Removes handler that was previously added withonRequest(handler).voidoffRequestFailed(Consumer<Request> handler) Removes handler that was previously added withonRequestFailed(handler).voidoffRequestFinished(Consumer<Request> handler) Removes handler that was previously added withonRequestFinished(handler).voidoffResponse(Consumer<Response> handler) Removes handler that was previously added withonResponse(handler).voidoffWebSocket(Consumer<WebSocket> handler) Removes handler that was previously added withonWebSocket(handler).voidRemoves handler that was previously added withonWorker(handler).voidonceDialog(Consumer<Dialog> handler) Adds one-offDialoghandler.voidEmitted when the page closes.voidonConsoleMessage(Consumer<ConsoleMessage> handler) Emitted when JavaScript within the page calls one of console API methods, e.g.voidEmitted when the page crashes.voidEmitted when a JavaScript dialog appears, such asalert,prompt,confirmorbeforeunload.voidonDOMContentLoaded(Consumer<Page> handler) Emitted when the JavaScriptDOMContentLoadedevent is dispatched.voidonDownload(Consumer<Download> handler) Emitted when attachment download started.voidonFileChooser(Consumer<FileChooser> handler) Emitted when a file chooser is supposed to appear, such as after clicking the<input type=file>.voidonFrameAttached(Consumer<Frame> handler) Emitted when a frame is attached.voidonFrameDetached(Consumer<Frame> handler) Emitted when a frame is detached.voidonFrameNavigated(Consumer<Frame> handler) Emitted when a frame is navigated to a new url.voidEmitted when the JavaScriptloadevent is dispatched.voidonPageError(Consumer<String> handler) Emitted when an uncaught exception happens within the page.voidEmitted when the page opens a new tab or window.voidEmitted when a page issues a request.voidonRequestFailed(Consumer<Request> handler) Emitted when a request fails, for example by timing out.voidonRequestFinished(Consumer<Request> handler) Emitted when a request finishes successfully after downloading the response body.voidonResponse(Consumer<Response> handler) Emitted when [response] status and headers are received for a request.voidonWebSocket(Consumer<WebSocket> handler) Emitted whenWebSocketrequest is sent.voidEmitted when a dedicated WebWorker is spawned by the page.opener()Returns the opener for popup pages andnullfor others.voidpause()Pauses script execution.default byte[]pdf()Returns the PDF buffer.byte[]pdf(Page.PdfOptions options) Returns the PDF buffer.default voidFocuses the element, and then usesKeyboard.down()andKeyboard.up().voidpress(String selector, String key, Page.PressOptions options) Focuses the element, and then usesKeyboard.down()andKeyboard.up().default ElementHandlequerySelector(String selector) The method finds an element matching the specified selector within the page.querySelector(String selector, Page.QuerySelectorOptions options) The method finds an element matching the specified selector within the page.querySelectorAll(String selector) The method finds all elements matching the specified selector within the page.default Responsereload()This method reloads the current page, in the same way as if the user had triggered a browser refresh.reload(Page.ReloadOptions options) This method reloads the current page, in the same way as if the user had triggered a browser refresh.request()API testing helper associated with this page.default voidRouting provides the capability to modify network requests that are made by a page.voidroute(String url, Consumer<Route> handler, Page.RouteOptions options) Routing provides the capability to modify network requests that are made by a page.default voidRouting provides the capability to modify network requests that are made by a page.voidRouting provides the capability to modify network requests that are made by a page.default voidRouting provides the capability to modify network requests that are made by a page.voidroute(Pattern url, Consumer<Route> handler, Page.RouteOptions options) Routing provides the capability to modify network requests that are made by a page.default voidrouteFromHAR(Path har) If specified the network requests that are made in the page will be served from the HAR file.voidrouteFromHAR(Path har, Page.RouteFromHAROptions options) If specified the network requests that are made in the page will be served from the HAR file.default byte[]Returns the buffer with the captured screenshot.byte[]screenshot(Page.ScreenshotOptions options) Returns the buffer with the captured screenshot.selectOption(String selector, ElementHandle values) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, ElementHandle[] values) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, ElementHandle[] values, Page.SelectOptionOptions options) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, ElementHandle values, Page.SelectOptionOptions options) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, SelectOption values) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, SelectOption[] values) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, SelectOption[] values, Page.SelectOptionOptions options) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, SelectOption values, Page.SelectOptionOptions options) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, String values) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, String[] values) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, String[] values, Page.SelectOptionOptions options) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.selectOption(String selector, String values, Page.SelectOptionOptions options) This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default voidsetChecked(String selector, boolean checked) This method checks or unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.voidsetChecked(String selector, boolean checked, Page.SetCheckedOptions options) This method checks or unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidsetContent(String html) This method internally calls document.write(), inheriting all its specific characteristics and behaviors.voidsetContent(String html, Page.SetContentOptions options) This method internally calls document.write(), inheriting all its specific characteristics and behaviors.voidsetDefaultNavigationTimeout(double timeout) This setting will change the default maximum navigation time for the following methods and related shortcuts:Page.goBack()Page.goForward()Page.navigate()Page.reload()Page.setContent()Page.waitForNavigation()Page.waitForURL()voidsetDefaultTimeout(double timeout) This setting will change the default maximum time for all the methods acceptingtimeoutoption.voidsetExtraHTTPHeaders(Map<String, String> headers) The extra HTTP headers will be sent with every request the page initiates.default voidsetInputFiles(String selector, FilePayload files) Sets the value of the file input to these file paths or files.default voidsetInputFiles(String selector, FilePayload[] files) Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, FilePayload[] files, Page.SetInputFilesOptions options) Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, FilePayload files, Page.SetInputFilesOptions options) Sets the value of the file input to these file paths or files.default voidsetInputFiles(String selector, Path files) Sets the value of the file input to these file paths or files.default voidsetInputFiles(String selector, Path[] files) Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, Path[] files, Page.SetInputFilesOptions options) Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, Path files, Page.SetInputFilesOptions options) Sets the value of the file input to these file paths or files.voidsetViewportSize(int width, int height) In the case of multiple pages in a single browser, each page can have its own viewport size.default voidThis method taps an element matchingselectorby performing the following steps: Find an element matchingselector.voidtap(String selector, Page.TapOptions options) This method taps an element matchingselectorby performing the following steps: Find an element matchingselector.default StringtextContent(String selector) Returnselement.textContent.textContent(String selector, Page.TextContentOptions options) Returnselement.textContent.title()Returns the page's title.default voidDeprecated.voidtype(String selector, String text, Page.TypeOptions options) Deprecated.In most cases, you should useLocator.fill()instead.default voidThis method unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.voiduncheck(String selector, Page.UncheckOptions options) This method unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidRemoves a route created withPage.route().voidRemoves a route created withPage.route().default voidRemoves a route created withPage.route().voidRemoves a route created withPage.route().default voidRemoves a route created withPage.route().voidRemoves a route created withPage.route().url()video()Video object associated with this page.waitForClose(Page.WaitForCloseOptions options, Runnable callback) Performs action and waits for the Page to close.default PagewaitForClose(Runnable callback) Performs action and waits for the Page to close.default voidwaitForCondition(BooleanSupplier condition) The method will block until the condition returns true.voidwaitForCondition(BooleanSupplier condition, Page.WaitForConditionOptions options) The method will block until the condition returns true.waitForConsoleMessage(Page.WaitForConsoleMessageOptions options, Runnable callback) Performs action and waits for aConsoleMessageto be logged by in the page.default ConsoleMessagewaitForConsoleMessage(Runnable callback) Performs action and waits for aConsoleMessageto be logged by in the page.waitForDownload(Page.WaitForDownloadOptions options, Runnable callback) Performs action and waits for a newDownload.default DownloadwaitForDownload(Runnable callback) Performs action and waits for a newDownload.waitForFileChooser(Page.WaitForFileChooserOptions options, Runnable callback) Performs action and waits for a newFileChooserto be created.default FileChooserwaitForFileChooser(Runnable callback) Performs action and waits for a newFileChooserto be created.default JSHandlewaitForFunction(String expression) Returns when theexpressionreturns a truthy value.default JSHandlewaitForFunction(String expression, Object arg) Returns when theexpressionreturns a truthy value.waitForFunction(String expression, Object arg, Page.WaitForFunctionOptions options) Returns when theexpressionreturns a truthy value.default voidReturns when the required load state has been reached.default voidwaitForLoadState(LoadState state) Returns when the required load state has been reached.voidwaitForLoadState(LoadState state, Page.WaitForLoadStateOptions options) Returns when the required load state has been reached.waitForNavigation(Page.WaitForNavigationOptions options, Runnable callback) Deprecated.This method is inherently racy, please usePage.waitForURL()instead.default ResponsewaitForNavigation(Runnable callback) Deprecated.This method is inherently racy, please usePage.waitForURL()instead.waitForPopup(Page.WaitForPopupOptions options, Runnable callback) Performs action and waits for a popupPage.default PagewaitForPopup(Runnable callback) Performs action and waits for a popupPage.waitForRequest(String urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback) Waits for the matching request and returns it.default RequestwaitForRequest(String urlOrPredicate, Runnable callback) Waits for the matching request and returns it.waitForRequest(Predicate<Request> urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback) Waits for the matching request and returns it.default RequestwaitForRequest(Predicate<Request> urlOrPredicate, Runnable callback) Waits for the matching request and returns it.waitForRequest(Pattern urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback) Waits for the matching request and returns it.default RequestwaitForRequest(Pattern urlOrPredicate, Runnable callback) Waits for the matching request and returns it.waitForRequestFinished(Page.WaitForRequestFinishedOptions options, Runnable callback) Performs action and waits for aRequestto finish loading.default RequestwaitForRequestFinished(Runnable callback) Performs action and waits for aRequestto finish loading.waitForResponse(String urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback) Returns the matched response.default ResponsewaitForResponse(String urlOrPredicate, Runnable callback) Returns the matched response.waitForResponse(Predicate<Response> urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback) Returns the matched response.default ResponsewaitForResponse(Predicate<Response> urlOrPredicate, Runnable callback) Returns the matched response.waitForResponse(Pattern urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback) Returns the matched response.default ResponsewaitForResponse(Pattern urlOrPredicate, Runnable callback) Returns the matched response.default ElementHandlewaitForSelector(String selector) Returns when element specified by selector satisfiesstateoption.waitForSelector(String selector, Page.WaitForSelectorOptions options) Returns when element specified by selector satisfiesstateoption.voidwaitForTimeout(double timeout) Waits for the giventimeoutin milliseconds.default voidwaitForURL(String url) Waits for the main frame to navigate to the given URL.voidwaitForURL(String url, Page.WaitForURLOptions options) Waits for the main frame to navigate to the given URL.default voidwaitForURL(Predicate<String> url) Waits for the main frame to navigate to the given URL.voidwaitForURL(Predicate<String> url, Page.WaitForURLOptions options) Waits for the main frame to navigate to the given URL.default voidwaitForURL(Pattern url) Waits for the main frame to navigate to the given URL.voidwaitForURL(Pattern url, Page.WaitForURLOptions options) Waits for the main frame to navigate to the given URL.waitForWebSocket(Page.WaitForWebSocketOptions options, Runnable callback) Performs action and waits for a newWebSocket.default WebSocketwaitForWebSocket(Runnable callback) Performs action and waits for a newWebSocket.waitForWorker(Page.WaitForWorkerOptions options, Runnable callback) Performs action and waits for a newWorker.default WorkerwaitForWorker(Runnable callback) Performs action and waits for a newWorker.workers()This method returns all of the dedicated WebWorkers associated with the page.
-
Method Details
-
onClose
Emitted when the page closes. -
offClose
Removes handler that was previously added withonClose(handler). -
onConsoleMessage
Emitted when JavaScript within the page calls one of console API methods, e.g.console.logorconsole.dir. Also emitted if the page throws an error or a warning.The arguments passed into
console.logare available on theConsoleMessageevent handler argument.**Usage**
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' })"); -
offConsoleMessage
Removes handler that was previously added withonConsoleMessage(handler). -
onCrash
Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.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". } -
offCrash
Removes handler that was previously added withonCrash(handler). -
onDialog
Emitted when a JavaScript dialog appears, such asalert,prompt,confirmorbeforeunload. Listener **must** eitherDialog.accept()orDialog.dismiss()the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.**Usage**
page.onDialog(dialog -> { dialog.accept(); });NOTE: When no
Page.onDialog()orBrowserContext.onDialog()listeners are present, all dialogs are automatically dismissed. -
offDialog
Removes handler that was previously added withonDialog(handler). -
onDOMContentLoaded
Emitted when the JavaScriptDOMContentLoadedevent is dispatched. -
offDOMContentLoaded
Removes handler that was previously added withonDOMContentLoaded(handler). -
onDownload
Emitted when attachment download started. User can access basic file operations on downloaded content via the passedDownloadinstance. -
offDownload
Removes handler that was previously added withonDownload(handler). -
onFileChooser
Emitted when a file chooser is supposed to appear, such as after clicking the<input type=file>. Playwright can respond to it via setting the input files usingFileChooser.setFiles()that can be uploaded after that.page.onFileChooser(fileChooser -> { fileChooser.setFiles(Paths.get("/tmp/myfile.pdf")); }); -
offFileChooser
Removes handler that was previously added withonFileChooser(handler). -
onFrameAttached
Emitted when a frame is attached. -
offFrameAttached
Removes handler that was previously added withonFrameAttached(handler). -
onFrameDetached
Emitted when a frame is detached. -
offFrameDetached
Removes handler that was previously added withonFrameDetached(handler). -
onLoad
Emitted when the JavaScriptloadevent is dispatched. -
offLoad
Removes handler that was previously added withonLoad(handler). -
onPageError
Emitted when an uncaught exception happens within the page.// Log all uncaught errors to the terminal page.onPageError(exception -> { System.out.println("Uncaught exception: " + exception); }); // Navigate to a page with an exception. page.navigate("data:text/html,<script>throw new Error('Test')</script>"); -
offPageError
Removes handler that was previously added withonPageError(handler). -
onPopup
Emitted when the page opens a new tab or window. This event is emitted in addition to theBrowserContext.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.getByText("open the popup").click(); }); 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). -
offPopup
Removes handler that was previously added withonPopup(handler). -
onRequest
Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, seePage.route()orBrowserContext.route(). -
offRequest
Removes handler that was previously added withonRequest(handler). -
onRequestFailed
Emitted when a request fails, for example by timing out.page.onRequestFailed(request -> { System.out.println(request.url() + " " + request.failure()); });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 withPage.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. -
offRequestFailed
Removes handler that was previously added withonRequestFailed(handler). -
onRequestFinished
Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events isrequest,responseandrequestfinished. -
offRequestFinished
Removes handler that was previously added withonRequestFinished(handler). -
onResponse
Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events isrequest,responseandrequestfinished. -
offResponse
Removes handler that was previously added withonResponse(handler). -
onWebSocket
Emitted whenWebSocketrequest is sent. -
offWebSocket
Removes handler that was previously added withonWebSocket(handler). -
onWorker
Emitted when a dedicated WebWorker is spawned by the page. -
offWorker
Removes handler that was previously added withonWorker(handler). -
addInitScript
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. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed
Math.random.**Usage**
An example of overriding
Math.randombefore 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()andPage.addInitScript()is not defined.- Parameters:
script- Script to be evaluated in all pages in the browser context.- Since:
- v1.8
-
addInitScript
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. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed
Math.random.**Usage**
An example of overriding
Math.randombefore 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()andPage.addInitScript()is not defined.- Parameters:
script- Script to be evaluated in all pages in the browser context.- Since:
- v1.8
-
addScriptTag
Adds a<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.- Since:
- v1.8
-
addScriptTag
Adds a<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.- Since:
- v1.8
-
addStyleTag
Adds a<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.- Since:
- v1.8
-
addStyleTag
Adds a<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.- Since:
- v1.8
-
bringToFront
void bringToFront()Brings page to front (activates tab).- Since:
- v1.8
-
check
This method checks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
check
This method checks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
click
This method clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
click
This method clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
close
default void close()IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed. IfrunBeforeUnloadistruethe method will run unload handlers, but will **not** wait for the page to close.By default,
page.close()**does not** runbeforeunloadhandlers.NOTE: if
runBeforeUnloadis passed as true, abeforeunloaddialog might be summoned and should be handled manually viaPage.onDialog()event.- Specified by:
closein interfaceAutoCloseable- Since:
- v1.8
-
close
IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed. IfrunBeforeUnloadistruethe method will run unload handlers, but will **not** wait for the page to close.By default,
page.close()**does not** runbeforeunloadhandlers.NOTE: if
runBeforeUnloadis passed as true, abeforeunloaddialog might be summoned and should be handled manually viaPage.onDialog()event.- Since:
- v1.8
-
content
String content()Gets the full HTML contents of the page, including the doctype.- Since:
- v1.8
-
context
BrowserContext context()Get the browser context that the page belongs to.- Since:
- v1.8
-
dblclick
This method double clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to double click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. Note that if the first click of thedblclick()triggers a navigation event, this method will throw.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
page.dblclick()dispatches twoclickevents and a singledblclickevent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
dblclick
This method double clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to double click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. Note that if the first click of thedblclick()triggers a navigation event, this method will throw.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
page.dblclick()dispatches twoclickevents and a singledblclickevent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
dispatchEvent
The snippet below dispatches theclickevent on the element. Regardless of the visibility state of the element,clickis dispatched. This is equivalent to calling element.click().**Usage**
page.dispatchEvent("button#submit", "click");Under the hood, it creates an instance of an event based on the given
type, initializes it witheventInitproperties and dispatches it on the element. Events arecomposed,cancelableand bubble by default.Since
eventInitis event-specific, please refer to the events documentation for the lists of initial properties:You can also specify
JSHandleas 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);- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.type- DOM event type:"click","dragstart", etc.eventInit- Optional event-specific initialization properties.- Since:
- v1.8
-
dispatchEvent
The snippet below dispatches theclickevent on the element. Regardless of the visibility state of the element,clickis dispatched. This is equivalent to calling element.click().**Usage**
page.dispatchEvent("button#submit", "click");Under the hood, it creates an instance of an event based on the given
type, initializes it witheventInitproperties and dispatches it on the element. Events arecomposed,cancelableand bubble by default.Since
eventInitis event-specific, please refer to the events documentation for the lists of initial properties:You can also specify
JSHandleas 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);- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.type- DOM event type:"click","dragstart", etc.- Since:
- v1.8
-
dispatchEvent
void dispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options) The snippet below dispatches theclickevent on the element. Regardless of the visibility state of the element,clickis dispatched. This is equivalent to calling element.click().**Usage**
page.dispatchEvent("button#submit", "click");Under the hood, it creates an instance of an event based on the given
type, initializes it witheventInitproperties and dispatches it on the element. Events arecomposed,cancelableand bubble by default.Since
eventInitis event-specific, please refer to the events documentation for the lists of initial properties:You can also specify
JSHandleas 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);- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.type- DOM event type:"click","dragstart", etc.eventInit- Optional event-specific initialization properties.- Since:
- v1.8
-
dragAndDrop
This method drags the source element to the target element. It will first move to the source element, perform amousedown, then move to the target element and perform amouseup.**Usage**
page.dragAndDrop("#source", '#target'); // or specify exact positions relative to the top-left corners of the elements: page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions() .setSourcePosition(34, 7).setTargetPosition(10, 20));- Parameters:
source- A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.target- A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
dragAndDrop
This method drags the source element to the target element. It will first move to the source element, perform amousedown, then move to the target element and perform amouseup.**Usage**
page.dragAndDrop("#source", '#target'); // or specify exact positions relative to the top-left corners of the elements: page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions() .setSourcePosition(34, 7).setTargetPosition(10, 20));- Parameters:
source- A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.target- A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
emulateMedia
default void emulateMedia()This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.**Usage**
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"); // → falsepage.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- Since:
- v1.8
-
emulateMedia
This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.**Usage**
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"); // → falsepage.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- Since:
- v1.8
-
evalOnSelector
The method finds an element matching the specified selector within the page and passes it as a first argument toexpression. If no elements match the selector, the method throws an error. Returns the value ofexpression.If
expressionreturns a Promise, thenPage.evalOnSelector()would wait for the promise to resolve and return its value.**Usage**
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");- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.9
-
evalOnSelector
The method finds an element matching the specified selector within the page and passes it as a first argument toexpression. If no elements match the selector, the method throws an error. Returns the value ofexpression.If
expressionreturns a Promise, thenPage.evalOnSelector()would wait for the promise to resolve and return its value.**Usage**
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");- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.9
-
evalOnSelector
Object evalOnSelector(String selector, String expression, Object arg, Page.EvalOnSelectorOptions options) The method finds an element matching the specified selector within the page and passes it as a first argument toexpression. If no elements match the selector, the method throws an error. Returns the value ofexpression.If
expressionreturns a Promise, thenPage.evalOnSelector()would wait for the promise to resolve and return its value.**Usage**
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");- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.9
-
evalOnSelectorAll
The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument toexpression. Returns the result ofexpressioninvocation.If
expressionreturns a Promise, thenPage.evalOnSelectorAll()would wait for the promise to resolve and return its value.**Usage**
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.9
-
evalOnSelectorAll
The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument toexpression. Returns the result ofexpressioninvocation.If
expressionreturns a Promise, thenPage.evalOnSelectorAll()would wait for the promise to resolve and return its value.**Usage**
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.9
-
evaluate
Returns the value of theexpressioninvocation.If the function passed to the
Page.evaluate()returns a Promise, thenPage.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, thenPage.evaluate()resolves toundefined. Playwright also supports transferring some additional values that are not serializable byJSON:-0,NaN,Infinity,-Infinity.**Usage**
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"ElementHandleinstances can be passed as an argument to thePage.evaluate():ElementHandle bodyHandle = page.evaluate("document.body"); String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello")); bodyHandle.dispose();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.8
-
evaluate
Returns the value of theexpressioninvocation.If the function passed to the
Page.evaluate()returns a Promise, thenPage.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, thenPage.evaluate()resolves toundefined. Playwright also supports transferring some additional values that are not serializable byJSON:-0,NaN,Infinity,-Infinity.**Usage**
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"ElementHandleinstances can be passed as an argument to thePage.evaluate():ElementHandle bodyHandle = page.evaluate("document.body"); String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello")); bodyHandle.dispose();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
evaluateHandle
Returns the value of theexpressioninvocation as aJSHandle.The only difference between
Page.evaluate()andPage.evaluateHandle()is thatPage.evaluateHandle()returnsJSHandle.If the function passed to the
Page.evaluateHandle()returns a Promise, thenPage.evaluateHandle()would wait for the promise to resolve and return its value.**Usage**
// 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".JSHandleinstances can be passed as an argument to thePage.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();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.8
-
evaluateHandle
Returns the value of theexpressioninvocation as aJSHandle.The only difference between
Page.evaluate()andPage.evaluateHandle()is thatPage.evaluateHandle()returnsJSHandle.If the function passed to the
Page.evaluateHandle()returns a Promise, thenPage.evaluateHandle()would wait for the promise to resolve and return its value.**Usage**
// 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".JSHandleinstances can be passed as an argument to thePage.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();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
exposeBinding
The method adds a function callednameon thewindowobject of every frame in this page. When called, the function executescallbackand returns a Promise which resolves to the return value ofcallback. If thecallbackreturns a Promise, it will be awaited.The first argument of the
callbackfunction 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.**Usage**
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");- Parameters:
name- Name of the function on the window object.callback- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
exposeBinding
The method adds a function callednameon thewindowobject of every frame in this page. When called, the function executescallbackand returns a Promise which resolves to the return value ofcallback. If thecallbackreturns a Promise, it will be awaited.The first argument of the
callbackfunction 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.**Usage**
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");- Parameters:
name- Name of the function on the window object.callback- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
exposeFunction
The method adds a function callednameon thewindowobject of every frame in the page. When called, the function executescallbackand returns a Promise which resolves to the return value ofcallback.If the
callbackreturns a Promise, it will be awaited.See
BrowserContext.exposeFunction()for context-wide exposed function.NOTE: Functions installed via
Page.exposeFunction()survive navigations.**Usage**
An example of adding a
sha256function 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"); } } }- Parameters:
name- Name of the function on the window objectcallback- Callback function which will be called in Playwright's context.- Since:
- v1.8
-
fill
This method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent 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
Locator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- Value to fill for the<input>,<textarea>or[contenteditable]element.- Since:
- v1.8
-
fill
This method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent 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
Locator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- Value to fill for the<input>,<textarea>or[contenteditable]element.- Since:
- v1.8
-
focus
This method fetches an element withselectorand focuses it. If there's no element matchingselector, the method waits until a matching element appears in the DOM.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
focus
This method fetches an element withselectorand focuses it. If there's no element matchingselector, the method waits until a matching element appears in the DOM.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
frame
Returns frame matching the specified criteria. Eithernameorurlmust be specified.**Usage**
Frame frame = page.frame("frame-name");Frame frame = page.frameByUrl(Pattern.compile(".*domain.*");- Parameters:
name- Frame name specified in theiframe'snameattribute.- Since:
- v1.8
-
frameByUrl
Returns frame with matching URL.- Parameters:
url- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.- Since:
- v1.9
-
frameByUrl
Returns frame with matching URL.- Parameters:
url- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.- Since:
- v1.9
-
frameByUrl
Returns frame with matching URL.- Parameters:
url- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.- Since:
- v1.9
-
frameLocator
When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.**Usage**
Following snippet locates element with text "Submit" in the iframe with id
my-frame, like<iframe id="my-frame">:Locator locator = page.frameLocator("#my-iframe").getByText("Submit"); locator.click();- Parameters:
selector- A selector to use when resolving DOM element.- Since:
- v1.17
-
frames
An array of all frames attached to the page.- Since:
- v1.8
-
getAttribute
Returns element attribute value.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.name- Attribute name to get the value for.- Since:
- v1.8
-
getAttribute
Returns element attribute value.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.name- Attribute name to get the value for.- Since:
- v1.8
-
getByAltText
Allows locating elements by their alt text.**Usage**
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByAltText
Allows locating elements by their alt text.**Usage**
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByAltText
Allows locating elements by their alt text.**Usage**
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByAltText
Allows locating elements by their alt text.**Usage**
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.**Usage**
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.**Usage**
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.**Usage**
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.**Usage**
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
Allows locating input elements by the placeholder text.**Usage**
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
Allows locating input elements by the placeholder text.**Usage**
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
Allows locating input elements by the placeholder text.**Usage**
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
Allows locating input elements by the placeholder text.**Usage**
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByRole
Allows locating elements by their ARIA role, ARIA attributes and accessible name.**Usage**
Consider the following DOM structure.
You can locate each element by it's implicit role:
assertThat(page .getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Sign up"))) .isVisible(); page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setName("Subscribe")) .check(); page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName( Pattern.compile("submit", Pattern.CASE_INSENSITIVE))) .click();**Details**
Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting
roleand/oraria-*attributes to default values.- Parameters:
role- Required aria role.- Since:
- v1.27
-
getByRole
Allows locating elements by their ARIA role, ARIA attributes and accessible name.**Usage**
Consider the following DOM structure.
You can locate each element by it's implicit role:
assertThat(page .getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Sign up"))) .isVisible(); page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setName("Subscribe")) .check(); page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName( Pattern.compile("submit", Pattern.CASE_INSENSITIVE))) .click();**Details**
Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting
roleand/oraria-*attributes to default values.- Parameters:
role- Required aria role.- Since:
- v1.27
-
getByTestId
Locate element by the test id.**Usage**
Consider the following DOM structure.
You can locate the element by it's test id:
page.getByTestId("directions").click();**Details**
By default, the
data-testidattribute is used as a test id. UseSelectors.setTestIdAttribute()to configure a different test id attribute if necessary.- Parameters:
testId- Id to locate the element by.- Since:
- v1.27
-
getByTestId
Locate element by the test id.**Usage**
Consider the following DOM structure.
You can locate the element by it's test id:
page.getByTestId("directions").click();**Details**
By default, the
data-testidattribute is used as a test id. UseSelectors.setTestIdAttribute()to configure a different test id attribute if necessary.- Parameters:
testId- Id to locate the element by.- Since:
- v1.27
-
getByText
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.**Usage**
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))**Details**
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByText
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.**Usage**
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))**Details**
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByText
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.**Usage**
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))**Details**
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByText
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.**Usage**
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))**Details**
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
Allows locating elements by their title attribute.**Usage**
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
Allows locating elements by their title attribute.**Usage**
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
Allows locating elements by their title attribute.**Usage**
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
Allows locating elements by their title attribute.**Usage**
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
goBack
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returnsnull.Navigate to the previous page in history.
- Since:
- v1.8
-
goBack
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returnsnull.Navigate to the previous page in history.
- Since:
- v1.8
-
goForward
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returnsnull.Navigate to the next page in history.
- Since:
- v1.8
-
goForward
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returnsnull.Navigate to the next page in history.
- Since:
- v1.8
-
hover
This method hovers over an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to hover over the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
hover
This method hovers over an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to hover over the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
innerHTML
Returnselement.innerHTML.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
innerHTML
Returnselement.innerHTML.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
innerText
Returnselement.innerText.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
innerText
Returnselement.innerText.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
inputValue
Returnsinput.valuefor the selected<input>or<textarea>or<select>element.Throws for non-input elements. However, if the element is inside the
<label>element that has an associated control, returns the value of the control.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
inputValue
Returnsinput.valuefor the selected<input>or<textarea>or<select>element.Throws for non-input elements. However, if the element is inside the
<label>element that has an associated control, returns the value of the control.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
isChecked
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isChecked
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isClosed
boolean isClosed()Indicates that the page has been closed.- Since:
- v1.8
-
isDisabled
Returns whether the element is disabled, the opposite of enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isDisabled
Returns whether the element is disabled, the opposite of enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEditable
Returns whether the element is editable.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEditable
Returns whether the element is editable.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEnabled
Returns whether the element is enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEnabled
Returns whether the element is enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isHidden
Returns whether the element is hidden, the opposite of visible.selectorthat does not match any elements is considered hidden.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isHidden
Returns whether the element is hidden, the opposite of visible.selectorthat does not match any elements is considered hidden.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isVisible
Returns whether the element is visible.selectorthat does not match any elements is considered not visible.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isVisible
Returns whether the element is visible.selectorthat does not match any elements is considered not visible.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
keyboard
Keyboard keyboard()- Since:
- v1.8
-
locator
The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.- Parameters:
selector- A selector to use when resolving DOM element.- Since:
- v1.14
-
locator
The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.- Parameters:
selector- A selector to use when resolving DOM element.- Since:
- v1.14
-
mainFrame
Frame mainFrame()The page's main frame. Page is guaranteed to have a main frame which persists during navigations.- Since:
- v1.8
-
mouse
Mouse mouse()- Since:
- v1.8
-
onceDialog
Adds one-offDialoghandler. The handler will be removed immediately after nextDialogis 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:
Consumer<Dialog> handler = new Consumer<Dialog>() { @Override public void accept(Dialog dialog) { dialog.accept("foo"); page.offDialog(this); } }; page.onDialog(handler); // 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:')"));- Parameters:
handler- Receives theDialogobject, it **must** eitherDialog.accept()orDialog.dismiss()the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.- Since:
- v1.10
-
opener
Page opener()Returns the opener for popup pages andnullfor others. If the opener has been closed already the returnsnull.- Since:
- v1.8
-
pause
void pause()Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to callplaywright.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
headlessvalue in theBrowserType.launch().- Since:
- v1.9
-
pdf
default byte[] pdf()Returns the PDF buffer.NOTE: Generating a pdf is currently only supported in Chromium headless.
page.pdf()generates a pdf of the page withprintcss media. To generate a pdf withscreenmedia, callPage.emulateMedia()before callingpage.pdf():NOTE: By default,
page.pdf()generates a pdf with modified colors for printing. Use the-webkit-print-color-adjustproperty to force rendering of exact colors.**Usage**
// 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, andmarginoptions accept values labeled with units. Unlabeled values are treated as pixels.A few examples:
-
page.pdf({width: 100})- prints with width set to 100 pixels -
page.pdf({width: '100px'})- prints with width set to 100 pixels -
page.pdf({width: '10cm'})- prints with width set to 10 centimeters.
All possible units are:
-
px- pixel -
in- inch -
cm- centimeter -
mm- millimeter
The
formatoptions are:-
Letter: 8.5in x 11in -
Legal: 8.5in x 14in -
Tabloid: 11in x 17in -
Ledger: 17in x 11in -
A0: 33.1in x 46.8in -
A1: 23.4in x 33.1in -
A2: 16.54in x 23.4in -
A3: 11.7in x 16.54in -
A4: 8.27in x 11.7in -
A5: 5.83in x 8.27in -
A6: 4.13in x 5.83in
NOTE:
headerTemplateandfooterTemplatemarkup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.- Since:
- v1.8
-
-
pdf
Returns the PDF buffer.NOTE: Generating a pdf is currently only supported in Chromium headless.
page.pdf()generates a pdf of the page withprintcss media. To generate a pdf withscreenmedia, callPage.emulateMedia()before callingpage.pdf():NOTE: By default,
page.pdf()generates a pdf with modified colors for printing. Use the-webkit-print-color-adjustproperty to force rendering of exact colors.**Usage**
// 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, andmarginoptions accept values labeled with units. Unlabeled values are treated as pixels.A few examples:
-
page.pdf({width: 100})- prints with width set to 100 pixels -
page.pdf({width: '100px'})- prints with width set to 100 pixels -
page.pdf({width: '10cm'})- prints with width set to 10 centimeters.
All possible units are:
-
px- pixel -
in- inch -
cm- centimeter -
mm- millimeter
The
formatoptions are:-
Letter: 8.5in x 11in -
Legal: 8.5in x 14in -
Tabloid: 11in x 17in -
Ledger: 17in x 11in -
A0: 33.1in x 46.8in -
A1: 23.4in x 33.1in -
A2: 16.54in x 23.4in -
A3: 11.7in x 16.54in -
A4: 8.27in x 11.7in -
A5: 5.83in x 8.27in -
A6: 4.13in x 5.83in
NOTE:
headerTemplateandfooterTemplatemarkup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.- Since:
- v1.8
-
-
press
Focuses the element, and then usesKeyboard.down()andKeyboard.up().keycan specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of thekeyvalues 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
Shiftwill type the text that corresponds to thekeyin the upper case.If
keyis a single character, it is case-sensitive, so the valuesaandAwill generate different respective texts.Shortcuts such as
key: "Control+o"orkey: "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.**Usage**
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" )));- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.key- Name of the key to press or a character to generate, such asArrowLeftora.- Since:
- v1.8
-
press
Focuses the element, and then usesKeyboard.down()andKeyboard.up().keycan specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of thekeyvalues 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
Shiftwill type the text that corresponds to thekeyin the upper case.If
keyis a single character, it is case-sensitive, so the valuesaandAwill generate different respective texts.Shortcuts such as
key: "Control+o"orkey: "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.**Usage**
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" )));- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.key- Name of the key to press or a character to generate, such asArrowLeftora.- Since:
- v1.8
-
querySelector
The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves tonull. To wait for an element on the page, useLocator.waitFor().- Parameters:
selector- A selector to query for.- Since:
- v1.9
-
querySelector
The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves tonull. To wait for an element on the page, useLocator.waitFor().- Parameters:
selector- A selector to query for.- Since:
- v1.9
-
querySelectorAll
The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to[].- Parameters:
selector- A selector to query for.- Since:
- v1.9
-
reload
This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.- Since:
- v1.8
-
reload
This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.- Since:
- v1.8
-
request
APIRequestContext request()API testing helper associated with this page. This method returns the same instance asBrowserContext.request()on the page's context. SeeBrowserContext.request()for more details.- Since:
- v1.16
-
route
Routing provides the capability to modify network requests that are made by a page.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.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".**Usage**
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.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
Routing provides the capability to modify network requests that are made by a page.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.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".**Usage**
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.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
Routing provides the capability to modify network requests that are made by a page.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.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".**Usage**
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.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
Routing provides the capability to modify network requests that are made by a page.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.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".**Usage**
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.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
Routing provides the capability to modify network requests that are made by a page.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.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".**Usage**
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.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
Routing provides the capability to modify network requests that are made by a page.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.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".**Usage**
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.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
routeFromHAR
If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting
Browser.newContext.serviceWorkersto"block".- Parameters:
har- Path to a HAR file with prerecorded network data. Ifpathis a relative path, then it is resolved relative to the current working directory.- Since:
- v1.23
-
routeFromHAR
If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting
Browser.newContext.serviceWorkersto"block".- Parameters:
har- Path to a HAR file with prerecorded network data. Ifpathis a relative path, then it is resolved relative to the current working directory.- Since:
- v1.23
-
screenshot
default byte[] screenshot()Returns the buffer with the captured screenshot.- Since:
- v1.8
-
screenshot
Returns the buffer with the captured screenshot.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, ElementHandle[] values, Page.SelectOptionOptions options) This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
This method waits for an element matchingselector, 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
changeandinputevent once all the provided options have been selected.**Usage**
// Single selection matching the value or label 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"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
setChecked
This method checks or unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- If the element already has the right checked state, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked or unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.checked- Whether to check or uncheck the checkbox.- Since:
- v1.15
- Find an element matching
-
setChecked
This method checks or unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- If the element already has the right checked state, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked or unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.checked- Whether to check or uncheck the checkbox.- Since:
- v1.15
- Find an element matching
-
setContent
This method internally calls document.write(), inheriting all its specific characteristics and behaviors.- Parameters:
html- HTML markup to assign to the page.- Since:
- v1.8
-
setContent
This method internally calls document.write(), inheriting all its specific characteristics and behaviors.- Parameters:
html- HTML markup to assign to the page.- Since:
- v1.8
-
setDefaultTimeout
void setDefaultTimeout(double timeout) This setting will change the default maximum time for all the methods acceptingtimeoutoption.NOTE:
Page.setDefaultNavigationTimeout()takes priority overPage.setDefaultTimeout().- Parameters:
timeout- Maximum time in milliseconds- Since:
- v1.8
-
setExtraHTTPHeaders
The extra HTTP headers will be sent with every request the page initiates.NOTE:
Page.setExtraHTTPHeaders()does not guarantee the order of headers in the outgoing requests.- Parameters:
headers- An object containing additional HTTP headers to be sent with every request. All header values must be strings.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setViewportSize
void setViewportSize(int width, int height) In the case of multiple pages in a single browser, each page can have its own viewport size. However,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.setViewportSize()will also resetscreensize, useBrowser.newContext()withscreenandviewportparameters if you need better control of these properties.**Usage**
Page page = browser.newPage(); page.setViewportSize(640, 480); page.navigate("https://example.com");- Since:
- v1.8
-
tap
This method taps an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.touchscreen()to tap the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
Page.tap()the method will throw ifhasTouchoption of the browser context is false.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
tap
This method taps an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.touchscreen()to tap the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
Page.tap()the method will throw ifhasTouchoption of the browser context is false.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
textContent
Returnselement.textContent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
textContent
Returnselement.textContent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
title
String title()Returns the page's title.- Since:
- v1.8
-
touchscreen
Touchscreen touchscreen()- Since:
- v1.8
-
type
Deprecated.In most cases, you should useLocator.fill()instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case useLocator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.text- A text to type into a focused element.- Since:
- v1.8
-
type
Deprecated.In most cases, you should useLocator.fill()instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case useLocator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.text- A text to type into a focused element.- Since:
- v1.8
-
uncheck
This method unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
uncheck
This method unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
unroute
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.- Since:
- v1.8
-
unroute
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler- Optional handler function to route the request.- Since:
- v1.8
-
unroute
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.- Since:
- v1.8
-
unroute
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler- Optional handler function to route the request.- Since:
- v1.8
-
unroute
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.- Since:
- v1.8
-
unroute
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler- Optional handler function to route the request.- Since:
- v1.8
-
url
String url()- Since:
- v1.8
-
video
Video video()Video object associated with this page.- Since:
- v1.8
-
viewportSize
ViewportSize viewportSize()- Since:
- v1.8
-
waitForClose
Performs action and waits for the Page to close.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.11
-
waitForClose
Performs action and waits for the Page to close.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.11
-
waitForConsoleMessage
Performs action and waits for aConsoleMessageto be logged by in the page. If predicate is provided, it passesConsoleMessagevalue into thepredicatefunction and waits forpredicate(message)to return a truthy value. Will throw an error if the page is closed before thePage.onConsoleMessage()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForConsoleMessage
Performs action and waits for aConsoleMessageto be logged by in the page. If predicate is provided, it passesConsoleMessagevalue into thepredicatefunction and waits forpredicate(message)to return a truthy value. Will throw an error if the page is closed before thePage.onConsoleMessage()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForDownload
Performs action and waits for a newDownload. If predicate is provided, it passesDownloadvalue into thepredicatefunction and waits forpredicate(download)to return a truthy value. Will throw an error if the page is closed before the download event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForDownload
Performs action and waits for a newDownload. If predicate is provided, it passesDownloadvalue into thepredicatefunction and waits forpredicate(download)to return a truthy value. Will throw an error if the page is closed before the download event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForFileChooser
Performs action and waits for a newFileChooserto be created. If predicate is provided, it passesFileChooservalue into thepredicatefunction and waits forpredicate(fileChooser)to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForFileChooser
Performs action and waits for a newFileChooserto be created. If predicate is provided, it passesFileChooservalue into thepredicatefunction and waits forpredicate(fileChooser)to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForFunction
Returns when theexpressionreturns a truthy value. It resolves to a JSHandle of the truthy value.**Usage**
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);- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
waitForFunction
Returns when theexpressionreturns a truthy value. It resolves to a JSHandle of the truthy value.**Usage**
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);- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.8
-
waitForFunction
Returns when theexpressionreturns a truthy value. It resolves to a JSHandle of the truthy value.**Usage**
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);- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
waitForLoadState
Returns when the required load state has been reached.This resolves when the page reaches a required load state,
loadby default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.**Usage**
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation. page.waitForLoadState(); // The promise resolves after "load" event.Page popup = page.waitForPopup(() -> { page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup. }); // Wait for the "DOMContentLoaded" event popup.waitForLoadState(LoadState.DOMCONTENTLOADED); System.out.println(popup.title()); // Popup is ready to use.- Parameters:
state- Optional load state to wait for, defaults toload. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:-
"load"- wait for theloadevent to be fired. -
"domcontentloaded"- wait for theDOMContentLoadedevent to be fired. -
"networkidle"- **DISCOURAGED** wait until there are no network connections for at least500ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
-
- Since:
- v1.8
-
waitForLoadState
default void waitForLoadState()Returns when the required load state has been reached.This resolves when the page reaches a required load state,
loadby default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.**Usage**
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation. page.waitForLoadState(); // The promise resolves after "load" event.Page popup = page.waitForPopup(() -> { page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup. }); // Wait for the "DOMContentLoaded" event popup.waitForLoadState(LoadState.DOMCONTENTLOADED); System.out.println(popup.title()); // Popup is ready to use.- Since:
- v1.8
-
waitForLoadState
Returns when the required load state has been reached.This resolves when the page reaches a required load state,
loadby default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.**Usage**
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation. page.waitForLoadState(); // The promise resolves after "load" event.Page popup = page.waitForPopup(() -> { page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup. }); // Wait for the "DOMContentLoaded" event popup.waitForLoadState(LoadState.DOMCONTENTLOADED); System.out.println(popup.title()); // Popup is ready to use.- Parameters:
state- Optional load state to wait for, defaults toload. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:-
"load"- wait for theloadevent to be fired. -
"domcontentloaded"- wait for theDOMContentLoadedevent to be fired. -
"networkidle"- **DISCOURAGED** wait until there are no network connections for at least500ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
-
- Since:
- v1.8
-
waitForPopup
Performs action and waits for a popupPage. If predicate is provided, it passes [Popup] value into thepredicatefunction and waits forpredicate(page)to return a truthy value. Will throw an error if the page is closed before the popup event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForPopup
Performs action and waits for a popupPage. If predicate is provided, it passes [Popup] value into thepredicatefunction and waits forpredicate(page)to return a truthy value. Will throw an error if the page is closed before the popup event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForRequest
Waits for the matching request and returns it. See waiting for event for more details about events.**Usage**
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // 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.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Request waitForRequest(String urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback) Waits for the matching request and returns it. See waiting for event for more details about events.**Usage**
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // 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.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Waits for the matching request and returns it. See waiting for event for more details about events.**Usage**
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // 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.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Request waitForRequest(Pattern urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback) Waits for the matching request and returns it. See waiting for event for more details about events.**Usage**
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // 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.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Waits for the matching request and returns it. See waiting for event for more details about events.**Usage**
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // 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.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Request waitForRequest(Predicate<Request> urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback) Waits for the matching request and returns it. See waiting for event for more details about events.**Usage**
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // 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.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequestFinished
Performs action and waits for aRequestto finish loading. If predicate is provided, it passesRequestvalue into thepredicatefunction and waits forpredicate(request)to return a truthy value. Will throw an error if the page is closed before thePage.onRequestFinished()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.12
-
waitForRequestFinished
Performs action and waits for aRequestto finish loading. If predicate is provided, it passesRequestvalue into thepredicatefunction and waits forpredicate(request)to return a truthy value. Will throw an error if the page is closed before thePage.onRequestFinished()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.12
-
waitForResponse
Returns the matched response. See waiting for event for more details about events.**Usage**
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // 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.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Response waitForResponse(String urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback) Returns the matched response. See waiting for event for more details about events.**Usage**
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // 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.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Returns the matched response. See waiting for event for more details about events.**Usage**
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // 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.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Response waitForResponse(Pattern urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback) Returns the matched response. See waiting for event for more details about events.**Usage**
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // 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.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Returns the matched response. See waiting for event for more details about events.**Usage**
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // 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.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Response waitForResponse(Predicate<Response> urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback) Returns the matched response. See waiting for event for more details about events.**Usage**
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // 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.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForSelector
Returns when element specified by selector satisfiesstateoption. Returnsnullif waiting forhiddenordetached.NOTE: Playwright automatically waits for element to be ready before performing an action. Using
Locatorobjects and web-first assertions makes the code wait-for-selector-free.Wait for the
selectorto satisfystateoption (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the methodselectoralready satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for thetimeoutmilliseconds, the function will throw.**Usage**
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(); } } }- Parameters:
selector- A selector to query for.- Since:
- v1.8
-
waitForSelector
Returns when element specified by selector satisfiesstateoption. Returnsnullif waiting forhiddenordetached.NOTE: Playwright automatically waits for element to be ready before performing an action. Using
Locatorobjects and web-first assertions makes the code wait-for-selector-free.Wait for the
selectorto satisfystateoption (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the methodselectoralready satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for thetimeoutmilliseconds, the function will throw.**Usage**
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(); } } }- Parameters:
selector- A selector to query for.- Since:
- v1.8
-
waitForCondition
The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.**Usage**
Use the method to wait for a condition that depends on page events:
List<String> messages = new ArrayList<>(); page.onConsoleMessage(m -> messages.add(m.text())); page.getByText("Submit button").click(); page.waitForCondition(() -> messages.size() > 3);- Parameters:
condition- Condition to wait for.- Since:
- v1.32
-
waitForCondition
The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.**Usage**
Use the method to wait for a condition that depends on page events:
List<String> messages = new ArrayList<>(); page.onConsoleMessage(m -> messages.add(m.text())); page.getByText("Submit button").click(); page.waitForCondition(() -> messages.size() > 3);- Parameters:
condition- Condition to wait for.- Since:
- v1.32
-
waitForTimeout
void waitForTimeout(double timeout) Waits for the giventimeoutin 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.**Usage**
// wait for 1 second page.waitForTimeout(1000);- Parameters:
timeout- A timeout to wait for- Since:
- v1.8
-
waitForURL
Waits for the main frame to navigate to the given URL.**Usage**
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
Waits for the main frame to navigate to the given URL.**Usage**
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
Waits for the main frame to navigate to the given URL.**Usage**
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
Waits for the main frame to navigate to the given URL.**Usage**
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
Waits for the main frame to navigate to the given URL.**Usage**
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
Waits for the main frame to navigate to the given URL.**Usage**
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForWebSocket
Performs action and waits for a newWebSocket. If predicate is provided, it passesWebSocketvalue into thepredicatefunction and waits forpredicate(webSocket)to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForWebSocket
Performs action and waits for a newWebSocket. If predicate is provided, it passesWebSocketvalue into thepredicatefunction and waits forpredicate(webSocket)to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForWorker
Performs action and waits for a newWorker. If predicate is provided, it passesWorkervalue into thepredicatefunction and waits forpredicate(worker)to return a truthy value. Will throw an error if the page is closed before the worker event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForWorker
Performs action and waits for a newWorker. If predicate is provided, it passesWorkervalue into thepredicatefunction and waits forpredicate(worker)to return a truthy value. Will throw an error if the page is closed before the worker event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
workers
This method returns all of the dedicated WebWorkers associated with the page.NOTE: This does not contain ServiceWorkers
- Since:
- v1.8
-
Locator.fill()instead.