Class PageImpl
- All Implemented Interfaces:
Page,AutoCloseable
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescription(package private) static enumprivate classprivate classprivate classNested classes/interfaces inherited from interface com.microsoft.playwright.Page
Page.AddScriptTagOptions, Page.AddStyleTagOptions, Page.CheckOptions, Page.ClickOptions, Page.CloseOptions, Page.DblclickOptions, Page.DispatchEventOptions, Page.DragAndDropOptions, Page.EmulateMediaOptions, Page.EvalOnSelectorOptions, Page.ExposeBindingOptions, Page.FillOptions, Page.FocusOptions, Page.GetAttributeOptions, Page.GetByAltTextOptions, Page.GetByLabelOptions, Page.GetByPlaceholderOptions, Page.GetByRoleOptions, Page.GetByTextOptions, Page.GetByTitleOptions, Page.GoBackOptions, Page.GoForwardOptions, Page.HoverOptions, Page.InnerHTMLOptions, Page.InnerTextOptions, Page.InputValueOptions, Page.IsCheckedOptions, Page.IsDisabledOptions, Page.IsEditableOptions, Page.IsEnabledOptions, Page.IsHiddenOptions, Page.IsVisibleOptions, Page.LocatorOptions, Page.NavigateOptions, Page.PdfOptions, Page.PressOptions, Page.QuerySelectorOptions, Page.ReloadOptions, Page.RouteFromHAROptions, Page.RouteOptions, Page.ScreenshotOptions, Page.SelectOptionOptions, Page.SetCheckedOptions, Page.SetContentOptions, Page.SetInputFilesOptions, Page.TapOptions, Page.TextContentOptions, Page.TypeOptions, Page.UncheckOptions, Page.WaitForCloseOptions, Page.WaitForConditionOptions, Page.WaitForConsoleMessageOptions, Page.WaitForDownloadOptions, Page.WaitForFileChooserOptions, Page.WaitForFunctionOptions, Page.WaitForLoadStateOptions, Page.WaitForNavigationOptions, Page.WaitForPopupOptions, Page.WaitForRequestFinishedOptions, Page.WaitForRequestOptions, Page.WaitForResponseOptions, Page.WaitForSelectorOptions, Page.WaitForURLOptions, Page.WaitForWebSocketOptions, Page.WaitForWorkerOptions -
Field Summary
FieldsModifier and TypeFieldDescription(package private) final Map<String, BindingCallback> private final BrowserContextImplprivate booleanprivate final KeyboardImpl(package private) final ListenerCollection<PageImpl.EventType> private final FrameImplprivate final MouseImplprivate final PageImpl(package private) BrowserContextImplprivate final Routerprivate final TimeoutSettingsprivate final TouchscreenImplprivate VideoImplprivate ViewportSize(package private) final Waitable<?> Fields inherited from class com.microsoft.playwright.impl.ChannelOwner
connection, guid, initializer, type -
Constructor Summary
ConstructorsConstructorDescriptionPageImpl(ChannelOwner parent, String type, String guid, com.google.gson.JsonObject initializer) -
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 path) 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.private voidaddInitScriptImpl(String script) addScriptTag(Page.AddScriptTagOptions options) Adds a<script>tag into the page with the desired url or 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).voidcheck(String selector, Page.CheckOptions options) This method checks 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.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.(package private) <T> Waitable<T> createWaitableFrameDetach(Frame frame) (package private) <T> Waitable<T> createWaitableNavigationTimeout(Double timeout) (package private) <T> Waitable<T> createWaitableTimeout(Double timeout) (package private) <T> Waitable<T> voiddblclick(String selector, Page.DblclickOptions options) This method double clicks an element matchingselectorby performing the following steps: Find an element matchingselector.(package private) voiddidClose()voiddispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options) The snippet below dispatches theclickevent on the element.voiddragAndDrop(String source, String target, Page.DragAndDropOptions options) This method drags the source element to the target element.voidemulateMedia(Page.EmulateMediaOptions options) This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.private voidemulateMediaImpl(Page.EmulateMediaOptions options) evalOnSelector(String selector, String pageFunction, 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.evalOnSelectorAll(String selector, String pageFunction, 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.Returns the value of theexpressioninvocation.evaluateHandle(String pageFunction, Object arg) Returns the value of theexpressioninvocation as aJSHandle.private static final Map<PageImpl.EventType, String> voidexposeBinding(String name, BindingCallback playwrightBinding, Page.ExposeBindingOptions options) The method adds a function callednameon thewindowobject of every frame in this page.private voidexposeBindingImpl(String name, BindingCallback playwrightBinding, Page.ExposeBindingOptions options) voidexposeFunction(String name, FunctionCallback playwrightFunction) The method adds a function callednameon thewindowobject of every frame in the page.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.voidfocus(String selector, Page.FocusOptions options) This method fetches an element withselectorand focuses it.private VideoImplReturns frame matching the specified criteria.frameByUrl(String glob) Returns frame with matching URL.frameByUrl(Predicate<String> predicate) Returns frame with matching URL.frameByUrl(Pattern pattern) Returns frame with matching URL.private FrameframeFor(UrlMatcher matcher) 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.(package private) voidframeNavigated(FrameImpl frame) frames()An array of all frames attached to the page.getAttribute(String selector, String name, Page.GetAttributeOptions options) Returns element attribute value.getByAltText(String text, Page.GetByAltTextOptions options) Allows locating elements by their alt text.getByAltText(Pattern text, Page.GetByAltTextOptions options) Allows locating elements by their alt text.getByLabel(String text, Page.GetByLabelOptions options) 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.getByPlaceholder(String text, Page.GetByPlaceholderOptions options) Allows locating input elements by the placeholder text.getByPlaceholder(Pattern text, Page.GetByPlaceholderOptions options) Allows locating input elements by the placeholder text.getByRole(AriaRole role, Page.GetByRoleOptions options) getByTestId(String testId) Locate element by the test id.getByTestId(Pattern testId) Locate element by the test id.getByText(String text, Page.GetByTextOptions options) Allows locating elements that contain given text.getByText(Pattern text, Page.GetByTextOptions options) Allows locating elements that contain given text.getByTitle(String text, Page.GetByTitleOptions options) Allows locating elements by their title attribute.getByTitle(Pattern text, Page.GetByTitleOptions options) Allows locating elements by their title attribute.goBack(Page.GoBackOptions options) Returns the main resource response.(package private) ResponsegoBackImpl(Page.GoBackOptions options) goForward(Page.GoForwardOptions options) Returns the main resource response.(package private) ResponsegoForwardImpl(Page.GoForwardOptions options) protected voidhandleEvent(String event, com.google.gson.JsonObject params) voidhover(String selector, Page.HoverOptions options) This method hovers over an element matchingselectorby performing the following steps: Find an element matchingselector.innerHTML(String selector, Page.InnerHTMLOptions options) Returnselement.innerHTML.innerText(String selector, Page.InnerTextOptions options) Returnselement.innerText.inputValue(String selector, Page.InputValueOptions options) Returnsinput.valuefor the selected<input>or<textarea>or<select>element.booleanisChecked(String selector, Page.IsCheckedOptions options) Returns whether the element is checked.booleanisClosed()Indicates that the page has been closed.booleanisDisabled(String selector, Page.IsDisabledOptions options) Returns whether the element is disabled, the opposite of enabled.booleanisEditable(String selector, Page.IsEditableOptions options) Returns whether the element is editable.booleanisEnabled(String selector, Page.IsEnabledOptions options) Returns whether the element is enabled.booleanisHidden(String selector, Page.IsHiddenOptions options) Returns whether the element is hidden, the opposite of visible.booleanisVisible(String selector, Page.IsVisibleOptions options) Returns whether the element is visible.keyboard()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()navigate(String url, Page.NavigateOptions options) Returns the main resource response.(package private) voidnotifyPopup(PageImpl popup) 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.byte[]pdf(Page.PdfOptions options) Returns the PDF buffer.private byte[]pdfImpl(Page.PdfOptions options) voidpress(String selector, String key, Page.PressOptions options) Focuses the element, and then usesKeyboard.down()andKeyboard.up().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.reload(Page.ReloadOptions options) This method reloads the current page, in the same way as if the user had triggered a browser refresh.private ResponsereloadImpl(Page.ReloadOptions options) request()API testing helper associated with this page.private voidroute(UrlMatcher matcher, Consumer<Route> handler, Page.RouteOptions options) voidroute(String url, Consumer<Route> handler, Page.RouteOptions options) Routing 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.voidroute(Pattern url, Consumer<Route> handler, Page.RouteOptions options) Routing provides the capability to modify network requests that are made by a page.voidrouteFromHAR(Path har, Page.RouteFromHAROptions options) If specified the network requests that are made in the page will be served from the HAR file.byte[]screenshot(Page.ScreenshotOptions options) Returns the buffer with the captured screenshot.private byte[]screenshotImpl(Page.ScreenshotOptions 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 value, 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, SelectOption value, 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.selectOption(String selector, String value, 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.voidsetChecked(String selector, boolean checked, Page.SetCheckedOptions options) This method checks or unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.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.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.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.voidtap(String selector, Page.TapOptions options) This method taps an element matchingselectorby performing the following steps: Find an element matchingselector.textContent(String selector, Page.TextContentOptions options) Returnselement.textContent.title()Returns the page's title.voidtype(String selector, String text, Page.TypeOptions options) voiduncheck(String selector, Page.UncheckOptions options) This method unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.private voidunroute(UrlMatcher matcher, Consumer<Route> handler) voidRemoves a route created withPage.route().voidRemoves a route created withPage.route().voidRemoves a route created withPage.route().private voidurl()video()Video object associated with this page.waitForClose(Page.WaitForCloseOptions options, Runnable code) Performs action and waits for the Page to close.private PagewaitForCloseImpl(Page.WaitForCloseOptions options, Runnable code) voidwaitForCondition(BooleanSupplier predicate, Page.WaitForConditionOptions options) The method will block until the condition returns true.waitForConsoleMessage(Page.WaitForConsoleMessageOptions options, Runnable code) Performs action and waits for aConsoleMessageto be logged by in the page.private ConsoleMessagewaitForConsoleMessageImpl(Page.WaitForConsoleMessageOptions options, Runnable code) waitForDownload(Page.WaitForDownloadOptions options, Runnable code) Performs action and waits for a newDownload.private DownloadwaitForDownloadImpl(Page.WaitForDownloadOptions options, Runnable code) private <T> TwaitForEventWithTimeout(PageImpl.EventType eventType, Runnable code, Predicate<T> predicate, Double timeout) waitForFileChooser(Page.WaitForFileChooserOptions options, Runnable code) Performs action and waits for a newFileChooserto be created.private FileChooserwaitForFileChooserImpl(Page.WaitForFileChooserOptions options, Runnable code) waitForFunction(String pageFunction, Object arg, Page.WaitForFunctionOptions options) Returns when theexpressionreturns a truthy value.voidwaitForLoadState(LoadState state, Page.WaitForLoadStateOptions options) Returns when the required load state has been reached.waitForNavigation(Page.WaitForNavigationOptions options, Runnable code) private ResponsewaitForNavigationImpl(Logger logger, Runnable code, Page.WaitForNavigationOptions options) waitForPopup(Page.WaitForPopupOptions options, Runnable code) Performs action and waits for a popupPage.private PagewaitForPopupImpl(Page.WaitForPopupOptions options, Runnable code) private RequestwaitForRequest(UrlMatcher urlMatcher, Predicate<Request> predicate, Page.WaitForRequestOptions options, Runnable code) waitForRequest(String urlGlob, Page.WaitForRequestOptions options, Runnable code) Waits for the matching request and returns it.waitForRequest(Predicate<Request> predicate, Page.WaitForRequestOptions options, Runnable code) Waits for the matching request and returns it.waitForRequest(Pattern urlPattern, Page.WaitForRequestOptions options, Runnable code) Waits for the matching request and returns it.waitForRequestFinished(Page.WaitForRequestFinishedOptions options, Runnable code) Performs action and waits for aRequestto finish loading.private RequestwaitForRequestFinishedImpl(Page.WaitForRequestFinishedOptions options, Runnable code) private RequestwaitForRequestImpl(Predicate<Request> predicate, Page.WaitForRequestOptions options, Runnable code) private ResponsewaitForResponse(UrlMatcher urlMatcher, Predicate<Response> predicate, Page.WaitForResponseOptions options, Runnable code) waitForResponse(String urlGlob, Page.WaitForResponseOptions options, Runnable code) Returns the matched response.waitForResponse(Predicate<Response> predicate, Page.WaitForResponseOptions options, Runnable code) Returns the matched response.waitForResponse(Pattern urlPattern, Page.WaitForResponseOptions options, Runnable code) Returns the matched response.private ResponsewaitForResponseImpl(Predicate<Response> predicate, Page.WaitForResponseOptions options, Runnable code) waitForSelector(String selector, Page.WaitForSelectorOptions options) Returns when element specified by selector satisfiesstateoption.voidwaitForTimeout(double timeout) Waits for the giventimeoutin milliseconds.private voidwaitForURL(UrlMatcher matcher, Page.WaitForURLOptions options) voidwaitForURL(String url, Page.WaitForURLOptions options) 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.voidwaitForURL(Pattern url, Page.WaitForURLOptions options) Waits for the main frame to navigate to the given URL.waitForWebSocket(Page.WaitForWebSocketOptions options, Runnable code) Performs action and waits for a newWebSocket.private WebSocketwaitForWebSocketImpl(Page.WaitForWebSocketOptions options, Runnable code) waitForWorker(Page.WaitForWorkerOptions options, Runnable code) Performs action and waits for a newWorker.private WorkerwaitForWorkerImpl(Page.WaitForWorkerOptions options, Runnable code) workers()This method returns all of the dedicated WebWorkers associated with the page.Methods inherited from class com.microsoft.playwright.impl.ChannelOwner
adopt, disposeChannelOwner, runUntil, sendMessage, sendMessage, sendMessageAsync, toProtocolRef, withLogging, withWaitLoggingMethods inherited from class com.microsoft.playwright.impl.LoggingSupport
logApi, logApiIfEnabled, logWithTimestamp, withLoggingMethods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface com.microsoft.playwright.Page
addScriptTag, addStyleTag, check, click, close, dblclick, dispatchEvent, dispatchEvent, dragAndDrop, emulateMedia, evalOnSelector, evalOnSelector, evalOnSelectorAll, evaluate, evaluateHandle, exposeBinding, fill, focus, getAttribute, getByAltText, getByAltText, getByLabel, getByLabel, getByPlaceholder, getByPlaceholder, getByRole, getByText, getByText, getByTitle, getByTitle, goBack, goForward, hover, innerHTML, innerText, inputValue, isChecked, isDisabled, isEditable, isEnabled, isHidden, isVisible, locator, navigate, pdf, press, querySelector, reload, route, route, route, routeFromHAR, screenshot, selectOption, selectOption, selectOption, selectOption, selectOption, selectOption, setChecked, setContent, setInputFiles, setInputFiles, setInputFiles, setInputFiles, tap, textContent, type, uncheck, unroute, unroute, unroute, waitForClose, waitForCondition, waitForConsoleMessage, waitForDownload, waitForFileChooser, waitForFunction, waitForFunction, waitForLoadState, waitForLoadState, waitForNavigation, waitForPopup, waitForRequest, waitForRequest, waitForRequest, waitForRequestFinished, waitForResponse, waitForResponse, waitForResponse, waitForSelector, waitForURL, waitForURL, waitForURL, waitForWebSocket, waitForWorker
-
Field Details
-
browserContext
-
mainFrame
-
keyboard
-
mouse
-
touchscreen
-
waitableClosedOrCrashed
-
viewport
-
routes
-
frames
-
listeners
-
bindings
-
ownedContext
BrowserContextImpl ownedContext -
isClosed
private boolean isClosed -
workers
-
timeoutSettings
-
video
-
opener
-
-
Constructor Details
-
PageImpl
PageImpl(ChannelOwner parent, String type, String guid, com.google.gson.JsonObject initializer)
-
-
Method Details
-
eventSubscriptions
-
handleEvent
- Overrides:
handleEventin classChannelOwner
-
notifyPopup
-
didClose
void didClose() -
onClose
Description copied from interface:PageEmitted when the page closes. -
offClose
Description copied from interface:PageRemoves handler that was previously added withonClose(handler). -
onConsoleMessage
Description copied from interface:PageEmitted 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' })");- Specified by:
onConsoleMessagein interfacePage
-
offConsoleMessage
Description copied from interface:PageRemoves handler that was previously added withonConsoleMessage(handler).- Specified by:
offConsoleMessagein interfacePage
-
onCrash
Description copied from interface:PageEmitted 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
Description copied from interface:PageRemoves handler that was previously added withonCrash(handler). -
onDialog
Description copied from interface:PageEmitted 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
Description copied from interface:PageRemoves handler that was previously added withonDialog(handler). -
onDOMContentLoaded
Description copied from interface:PageEmitted when the JavaScriptDOMContentLoadedevent is dispatched.- Specified by:
onDOMContentLoadedin interfacePage
-
offDOMContentLoaded
Description copied from interface:PageRemoves handler that was previously added withonDOMContentLoaded(handler).- Specified by:
offDOMContentLoadedin interfacePage
-
onDownload
Description copied from interface:PageEmitted when attachment download started. User can access basic file operations on downloaded content via the passedDownloadinstance.- Specified by:
onDownloadin interfacePage
-
offDownload
Description copied from interface:PageRemoves handler that was previously added withonDownload(handler).- Specified by:
offDownloadin interfacePage
-
onFileChooser
Description copied from interface:PageEmitted 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")); });- Specified by:
onFileChooserin interfacePage
-
offFileChooser
Description copied from interface:PageRemoves handler that was previously added withonFileChooser(handler).- Specified by:
offFileChooserin interfacePage
-
onFrameAttached
Description copied from interface:PageEmitted when a frame is attached.- Specified by:
onFrameAttachedin interfacePage
-
offFrameAttached
Description copied from interface:PageRemoves handler that was previously added withonFrameAttached(handler).- Specified by:
offFrameAttachedin interfacePage
-
onFrameDetached
Description copied from interface:PageEmitted when a frame is detached.- Specified by:
onFrameDetachedin interfacePage
-
offFrameDetached
Description copied from interface:PageRemoves handler that was previously added withonFrameDetached(handler).- Specified by:
offFrameDetachedin interfacePage
-
onLoad
Description copied from interface:PageEmitted when the JavaScriptloadevent is dispatched. -
offLoad
Description copied from interface:PageRemoves handler that was previously added withonLoad(handler). -
onPageError
Description copied from interface:PageEmitted 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>");- Specified by:
onPageErrorin interfacePage
-
offPageError
Description copied from interface:PageRemoves handler that was previously added withonPageError(handler).- Specified by:
offPageErrorin interfacePage
-
onPopup
Description copied from interface:PageEmitted 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
Description copied from interface:PageRemoves handler that was previously added withonPopup(handler). -
onRequest
Description copied from interface:PageEmitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, seePage.route()orBrowserContext.route(). -
offRequest
Description copied from interface:PageRemoves handler that was previously added withonRequest(handler).- Specified by:
offRequestin interfacePage
-
onRequestFailed
Description copied from interface:PageEmitted 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.- Specified by:
onRequestFailedin interfacePage
-
offRequestFailed
Description copied from interface:PageRemoves handler that was previously added withonRequestFailed(handler).- Specified by:
offRequestFailedin interfacePage
-
onRequestFinished
Description copied from interface:PageEmitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events isrequest,responseandrequestfinished.- Specified by:
onRequestFinishedin interfacePage
-
offRequestFinished
Description copied from interface:PageRemoves handler that was previously added withonRequestFinished(handler).- Specified by:
offRequestFinishedin interfacePage
-
onResponse
Description copied from interface:PageEmitted when [response] status and headers are received for a request. For a successful response, the sequence of events isrequest,responseandrequestfinished.- Specified by:
onResponsein interfacePage
-
offResponse
Description copied from interface:PageRemoves handler that was previously added withonResponse(handler).- Specified by:
offResponsein interfacePage
-
onWebSocket
Description copied from interface:PageEmitted whenWebSocketrequest is sent.- Specified by:
onWebSocketin interfacePage
-
offWebSocket
Description copied from interface:PageRemoves handler that was previously added withonWebSocket(handler).- Specified by:
offWebSocketin interfacePage
-
onWorker
Description copied from interface:PageEmitted when a dedicated WebWorker is spawned by the page. -
offWorker
Description copied from interface:PageRemoves handler that was previously added withonWorker(handler). -
waitForClose
Description copied from interface:PagePerforms action and waits for the Page to close.- Specified by:
waitForClosein interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForCloseImpl
-
waitForConsoleMessage
public ConsoleMessage waitForConsoleMessage(Page.WaitForConsoleMessageOptions options, Runnable code) Description copied from interface:PagePerforms 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.- Specified by:
waitForConsoleMessagein interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForConsoleMessageImpl
private ConsoleMessage waitForConsoleMessageImpl(Page.WaitForConsoleMessageOptions options, Runnable code) -
waitForDownload
Description copied from interface:PagePerforms 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.- Specified by:
waitForDownloadin interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForDownloadImpl
-
waitForFileChooser
Description copied from interface:PagePerforms 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.- Specified by:
waitForFileChooserin interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForFileChooserImpl
-
waitForPopup
Description copied from interface:PagePerforms 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.- Specified by:
waitForPopupin interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForPopupImpl
-
waitForWebSocket
Description copied from interface:PagePerforms 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.- Specified by:
waitForWebSocketin interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForWebSocketImpl
-
waitForWorker
Description copied from interface:PagePerforms 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.- Specified by:
waitForWorkerin interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForWorkerImpl
-
waitForEventWithTimeout
private <T> T waitForEventWithTimeout(PageImpl.EventType eventType, Runnable code, Predicate<T> predicate, Double timeout) -
close
Description copied from interface:PageIfrunBeforeUnloadisfalse, 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. -
querySelector
Description copied from interface:PageThe 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().- Specified by:
querySelectorin interfacePage- Parameters:
selector- A selector to query for.
-
querySelectorAll
Description copied from interface:PageThe method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to[].- Specified by:
querySelectorAllin interfacePage- Parameters:
selector- A selector to query for.
-
evalOnSelector
public Object evalOnSelector(String selector, String pageFunction, Object arg, Page.EvalOnSelectorOptions options) Description copied from interface:PageThe 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");- Specified by:
evalOnSelectorin interfacePage- Parameters:
selector- A selector to query for.pageFunction- 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.
-
evalOnSelectorAll
Description copied from interface:PageThe 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);- Specified by:
evalOnSelectorAllin interfacePage- Parameters:
selector- A selector to query for.pageFunction- 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.
-
addInitScript
Description copied from interface:PageAdds 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.- Specified by:
addInitScriptin interfacePage- Parameters:
script- Script to be evaluated in all pages in the browser context.
-
addInitScript
Description copied from interface:PageAdds 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.- Specified by:
addInitScriptin interfacePage- Parameters:
path- Script to be evaluated in all pages in the browser context.
-
addInitScriptImpl
-
addScriptTag
Description copied from interface:PageAdds 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.- Specified by:
addScriptTagin interfacePage
-
addStyleTag
Description copied from interface:PageAdds 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.- Specified by:
addStyleTagin interfacePage
-
bringToFront
public void bringToFront()Description copied from interface:PageBrings page to front (activates tab).- Specified by:
bringToFrontin interfacePage
-
check
Description copied from interface:PageThis 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. - Find an element matching
-
click
Description copied from interface:PageThis 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. - Find an element matching
-
content
Description copied from interface:PageGets the full HTML contents of the page, including the doctype. -
context
Description copied from interface:PageGet the browser context that the page belongs to. -
dblclick
Description copied from interface:PageThis 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. - Find an element matching
-
dispatchEvent
public void dispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options) Description copied from interface:PageThe 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);- Specified by:
dispatchEventin interfacePage- 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.
-
emulateMedia
Description copied from interface:PageThis 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- Specified by:
emulateMediain interfacePage
-
emulateMediaImpl
-
evaluate
Description copied from interface:PageReturns 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(); -
evaluateHandle
Description copied from interface:PageReturns 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();- Specified by:
evaluateHandlein interfacePage- Parameters:
pageFunction- 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.
-
exposeBinding
public void exposeBinding(String name, BindingCallback playwrightBinding, Page.ExposeBindingOptions options) Description copied from interface:PageThe 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");- Specified by:
exposeBindingin interfacePage- Parameters:
name- Name of the function on the window object.playwrightBinding- Callback function that will be called in the Playwright's context.
-
exposeBindingImpl
private void exposeBindingImpl(String name, BindingCallback playwrightBinding, Page.ExposeBindingOptions options) -
exposeFunction
Description copied from interface:PageThe 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"); } } }- Specified by:
exposeFunctionin interfacePage- Parameters:
name- Name of the function on the window objectplaywrightFunction- Callback function which will be called in Playwright's context.
-
fill
Description copied from interface:PageThis 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(). -
focus
Description copied from interface:PageThis method fetches an element withselectorand focuses it. If there's no element matchingselector, the method waits until a matching element appears in the DOM. -
frame
Description copied from interface:PageReturns frame matching the specified criteria. Eithernameorurlmust be specified.**Usage**
Frame frame = page.frame("frame-name");Frame frame = page.frameByUrl(Pattern.compile(".*domain.*"); -
frameByUrl
Description copied from interface:PageReturns frame with matching URL.- Specified by:
frameByUrlin interfacePage- Parameters:
glob- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.
-
frameByUrl
Description copied from interface:PageReturns frame with matching URL.- Specified by:
frameByUrlin interfacePage- Parameters:
pattern- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.
-
frameByUrl
Description copied from interface:PageReturns frame with matching URL.- Specified by:
frameByUrlin interfacePage- Parameters:
predicate- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.
-
frameLocator
Description copied from interface:PageWhen 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();- Specified by:
frameLocatorin interfacePage- Parameters:
selector- A selector to use when resolving DOM element.
-
frameFor
-
frames
Description copied from interface:PageAn array of all frames attached to the page. -
getAttribute
Description copied from interface:PageReturns element attribute value.- Specified by:
getAttributein interfacePage- 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.
-
getByAltText
Description copied from interface:PageAllows 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();- Specified by:
getByAltTextin interfacePage- Parameters:
text- Text to locate the element for.
-
getByAltText
Description copied from interface:PageAllows 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();- Specified by:
getByAltTextin interfacePage- Parameters:
text- Text to locate the element for.
-
getByLabel
Description copied from interface:PageAllows 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");- Specified by:
getByLabelin interfacePage- Parameters:
text- Text to locate the element for.
-
getByLabel
Description copied from interface:PageAllows 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");- Specified by:
getByLabelin interfacePage- Parameters:
text- Text to locate the element for.
-
getByPlaceholder
Description copied from interface:PageAllows 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");- Specified by:
getByPlaceholderin interfacePage- Parameters:
text- Text to locate the element for.
-
getByPlaceholder
Description copied from interface:PageAllows 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");- Specified by:
getByPlaceholderin interfacePage- Parameters:
text- Text to locate the element for.
-
getByRole
Description copied from interface:PageAllows 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. -
getByTestId
Description copied from interface:PageLocate 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.- Specified by:
getByTestIdin interfacePage- Parameters:
testId- Id to locate the element by.
-
getByTestId
Description copied from interface:PageLocate 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.- Specified by:
getByTestIdin interfacePage- Parameters:
testId- Id to locate the element by.
-
getByText
Description copied from interface:PageAllows 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">. -
getByText
Description copied from interface:PageAllows 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">. -
getByTitle
Description copied from interface:PageAllows 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");- Specified by:
getByTitlein interfacePage- Parameters:
text- Text to locate the element for.
-
getByTitle
Description copied from interface:PageAllows 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");- Specified by:
getByTitlein interfacePage- Parameters:
text- Text to locate the element for.
-
goBack
Description copied from interface:PageReturns 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.
-
goBackImpl
-
goForward
Description copied from interface:PageReturns 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.
-
goForwardImpl
-
hover
Description copied from interface:PageThis 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. - Find an element matching
-
dragAndDrop
Description copied from interface:PageThis 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));- Specified by:
dragAndDropin interfacePage- 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.
-
innerHTML
Description copied from interface:PageReturnselement.innerHTML. -
innerText
Description copied from interface:PageReturnselement.innerText. -
inputValue
Description copied from interface:PageReturnsinput.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.- Specified by:
inputValuein interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
isChecked
Description copied from interface:PageReturns whether the element is checked. Throws if the element is not a checkbox or radio input. -
isClosed
public boolean isClosed()Description copied from interface:PageIndicates that the page has been closed. -
isDisabled
Description copied from interface:PageReturns whether the element is disabled, the opposite of enabled.- Specified by:
isDisabledin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
isEditable
Description copied from interface:PageReturns whether the element is editable.- Specified by:
isEditablein interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
isEnabled
Description copied from interface:PageReturns whether the element is enabled. -
isHidden
Description copied from interface:PageReturns whether the element is hidden, the opposite of visible.selectorthat does not match any elements is considered hidden. -
isVisible
Description copied from interface:PageReturns whether the element is visible.selectorthat does not match any elements is considered not visible. -
keyboard
-
locator
Description copied from interface:PageThe 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. -
mainFrame
Description copied from interface:PageThe page's main frame. Page is guaranteed to have a main frame which persists during navigations. -
mouse
-
opener
Description copied from interface:PageReturns the opener for popup pages andnullfor others. If the opener has been closed already the returnsnull. -
pause
public void pause()Description copied from interface:PagePauses 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(). -
pdf
Description copied from interface:PageReturns 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. -
-
pdfImpl
-
press
Description copied from interface:PageFocuses 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" ))); -
reload
Description copied from interface:PageThis 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. -
request
Description copied from interface:PageAPI testing helper associated with this page. This method returns the same instance asBrowserContext.request()on the page's context. SeeBrowserContext.request()for more details. -
reloadImpl
-
route
Description copied from interface:PageRouting 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.
- Specified by:
routein interfacePage- 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.
-
route
Description copied from interface:PageRouting 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.
- Specified by:
routein interfacePage- 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.
-
route
Description copied from interface:PageRouting 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.
- Specified by:
routein interfacePage- 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.
-
routeFromHAR
Description copied from interface:PageIf 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".- Specified by:
routeFromHARin interfacePage- 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.
-
route
-
screenshot
Description copied from interface:PageReturns the buffer with the captured screenshot.- Specified by:
screenshotin interfacePage
-
selectOption
Description copied from interface:PageThis 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"});- Specified by:
selectOptionin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- 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.
-
selectOption
public List<String> selectOption(String selector, ElementHandle value, Page.SelectOptionOptions options) Description copied from interface:PageThis 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"});- Specified by:
selectOptionin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- 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.
-
selectOption
public List<String> selectOption(String selector, String[] values, Page.SelectOptionOptions options) Description copied from interface:PageThis 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"});- Specified by:
selectOptionin interfacePage- 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.
-
selectOption
public List<String> selectOption(String selector, SelectOption value, Page.SelectOptionOptions options) Description copied from interface:PageThis 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"});- Specified by:
selectOptionin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- 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.
-
screenshotImpl
-
selectOption
public List<String> selectOption(String selector, SelectOption[] values, Page.SelectOptionOptions options) Description copied from interface:PageThis 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"});- Specified by:
selectOptionin interfacePage- 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.
-
selectOption
public List<String> selectOption(String selector, ElementHandle[] values, Page.SelectOptionOptions options) Description copied from interface:PageThis 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"});- Specified by:
selectOptionin interfacePage- 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.
-
setChecked
Description copied from interface:PageThis 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.- Specified by:
setCheckedin interfacePage- 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.
- Find an element matching
-
setContent
Description copied from interface:PageThis method internally calls document.write(), inheriting all its specific characteristics and behaviors.- Specified by:
setContentin interfacePage- Parameters:
html- HTML markup to assign to the page.
-
setDefaultTimeout
public void setDefaultTimeout(double timeout) Description copied from interface:PageThis setting will change the default maximum time for all the methods acceptingtimeoutoption.NOTE:
Page.setDefaultNavigationTimeout()takes priority overPage.setDefaultTimeout().- Specified by:
setDefaultTimeoutin interfacePage- Parameters:
timeout- Maximum time in milliseconds
-
setExtraHTTPHeaders
Description copied from interface:PageThe 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.- Specified by:
setExtraHTTPHeadersin interfacePage- Parameters:
headers- An object containing additional HTTP headers to be sent with every request. All header values must be strings.
-
setInputFiles
Description copied from interface:PageSets 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.- Specified by:
setInputFilesin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
setInputFiles
Description copied from interface:PageSets 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.- Specified by:
setInputFilesin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
setInputFiles
Description copied from interface:PageSets 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.- Specified by:
setInputFilesin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
setInputFiles
Description copied from interface:PageSets 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.- Specified by:
setInputFilesin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
setViewportSize
public void setViewportSize(int width, int height) Description copied from interface:PageIn 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");- Specified by:
setViewportSizein interfacePage
-
tap
Description copied from interface:PageThis 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. - Find an element matching
-
textContent
Description copied from interface:PageReturnselement.textContent.- Specified by:
textContentin interfacePage- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
-
title
Description copied from interface:PageReturns the page's title. -
touchscreen
- Specified by:
touchscreenin interfacePage
-
type
-
uncheck
Description copied from interface:PageThis 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. - Find an element matching
-
unroute
Description copied from interface:PageRemoves a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl. -
unroute
Description copied from interface:PageRemoves a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl. -
unroute
Description copied from interface:PageRemoves a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl. -
unroute
-
updateInterceptionPatterns
private void updateInterceptionPatterns() -
url
-
forceVideo
-
video
Description copied from interface:PageVideo object associated with this page. -
viewportSize
- Specified by:
viewportSizein interfacePage
-
createWaitableTimeout
-
waitForFunction
public JSHandle waitForFunction(String pageFunction, Object arg, Page.WaitForFunctionOptions options) Description copied from interface:PageReturns 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);- Specified by:
waitForFunctionin interfacePage- Parameters:
pageFunction- 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.
-
waitForLoadState
Description copied from interface:PageReturns 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.- Specified by:
waitForLoadStatein interfacePage- 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.
-
-
createWaitableFrameDetach
-
createWaitForCloseHelper
-
waitForRequest
Description copied from interface:PageWaits 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(); });- Specified by:
waitForRequestin interfacePage- Parameters:
urlGlob- 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.code- Callback that performs the action triggering the event.
-
waitForRequest
public Request waitForRequest(Pattern urlPattern, Page.WaitForRequestOptions options, Runnable code) Description copied from interface:PageWaits 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(); });- Specified by:
waitForRequestin interfacePage- Parameters:
urlPattern- 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.code- Callback that performs the action triggering the event.
-
waitForRequest
public Request waitForRequest(Predicate<Request> predicate, Page.WaitForRequestOptions options, Runnable code) Description copied from interface:PageWaits 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(); });- Specified by:
waitForRequestin interfacePage- Parameters:
predicate- 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.code- Callback that performs the action triggering the event.
-
waitForRequest
private Request waitForRequest(UrlMatcher urlMatcher, Predicate<Request> predicate, Page.WaitForRequestOptions options, Runnable code) -
waitForRequestImpl
private Request waitForRequestImpl(Predicate<Request> predicate, Page.WaitForRequestOptions options, Runnable code) -
waitForRequestFinished
Description copied from interface:PagePerforms 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.- Specified by:
waitForRequestFinishedin interfacePage- Parameters:
code- Callback that performs the action triggering the event.
-
waitForRequestFinishedImpl
private Request waitForRequestFinishedImpl(Page.WaitForRequestFinishedOptions options, Runnable code) -
waitForResponse
Description copied from interface:PageReturns 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(); });- Specified by:
waitForResponsein interfacePage- Parameters:
urlGlob- 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.code- Callback that performs the action triggering the event.
-
waitForResponse
public Response waitForResponse(Pattern urlPattern, Page.WaitForResponseOptions options, Runnable code) Description copied from interface:PageReturns 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(); });- Specified by:
waitForResponsein interfacePage- Parameters:
urlPattern- 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.code- Callback that performs the action triggering the event.
-
waitForResponse
public Response waitForResponse(Predicate<Response> predicate, Page.WaitForResponseOptions options, Runnable code) Description copied from interface:PageReturns 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(); });- Specified by:
waitForResponsein interfacePage- Parameters:
predicate- 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.code- Callback that performs the action triggering the event.
-
waitForResponse
private Response waitForResponse(UrlMatcher urlMatcher, Predicate<Response> predicate, Page.WaitForResponseOptions options, Runnable code) -
waitForResponseImpl
private Response waitForResponseImpl(Predicate<Response> predicate, Page.WaitForResponseOptions options, Runnable code) -
waitForSelector
Description copied from interface:PageReturns 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(); } } }- Specified by:
waitForSelectorin interfacePage- Parameters:
selector- A selector to query for.
-
waitForCondition
Description copied from interface:PageThe 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);- Specified by:
waitForConditionin interfacePage- Parameters:
predicate- Condition to wait for.
-
waitForTimeout
public void waitForTimeout(double timeout) Description copied from interface:PageWaits 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);- Specified by:
waitForTimeoutin interfacePage- Parameters:
timeout- A timeout to wait for
-
waitForURL
Description copied from interface:PageWaits 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");- Specified by:
waitForURLin interfacePage- 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.
-
waitForURL
Description copied from interface:PageWaits 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");- Specified by:
waitForURLin interfacePage- 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.
-
waitForURL
Description copied from interface:PageWaits 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");- Specified by:
waitForURLin interfacePage- 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.
-
waitForURL
-
workers
Description copied from interface:PageThis method returns all of the dedicated WebWorkers associated with the page.NOTE: This does not contain ServiceWorkers
-
onceDialog
Description copied from interface:PageAdds 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:')"));- Specified by:
onceDialogin interfacePage- 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.
-