Interface Page
-
- All Superinterfaces:
AutoCloseable
public interface Page extends AutoCloseable
Page provides methods to interact with a single tab in aBrowser, or an extension background page in Chromium. OneBrowserinstance might have multiplePageinstances.This example creates a page, navigates it to a URL, and then saves a screenshot:
import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch(); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.navigate("https://example.com"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png"))); browser.close(); } } }The Page class emits various events (described below) which can be handled using any of Node's native
EventEmittermethods, such ason,onceorremoveListener.This example logs a message for a single page
loadevent:page.onLoad(p -> System.out.println("Page loaded!"));To unsubscribe from events use the
removeListenermethod:Consumer<Request> logRequest = interceptedRequest -> { System.out.println("A request was made: " + interceptedRequest.url()); }; page.onRequest(logRequest); // Sometime later... page.offRequest(logRequest);
-
-
Nested Class Summary
-
Method Summary
All Methods Instance Methods Abstract Methods Default Methods Deprecated Methods Modifier and Type Method Description voidaddInitScript(String script)Adds a script which would be evaluated in one of the following scenarios: Whenever the page is navigated. Whenever the child frame is attached or navigated.voidaddInitScript(Path script)Adds a script which would be evaluated in one of the following scenarios: Whenever the page is navigated. Whenever the child frame is attached or navigated.default voidaddLocatorHandler(Locator locator, Consumer<Locator> handler)When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g.voidaddLocatorHandler(Locator locator, Consumer<Locator> handler, Page.AddLocatorHandlerOptions options)When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g.default ElementHandleaddScriptTag()Adds a<script>tag into the page with the desired url or content.ElementHandleaddScriptTag(Page.AddScriptTagOptions options)Adds a<script>tag into the page with the desired url or content.default ElementHandleaddStyleTag()Adds a<link rel="stylesheet">tag into the page with the desired url or a<style type="text/css">tag with the content.ElementHandleaddStyleTag(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.voidbringToFront()Brings page to front (activates tab).default voidcheck(String selector)This method checks an element matchingselectorby performing the following steps: Find an element matchingselector.voidcheck(String selector, Page.CheckOptions options)This method checks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidclick(String selector)This method clicks an element matchingselectorby performing the following steps: Find an element matchingselector.voidclick(String selector, Page.ClickOptions options)This method clicks an element matchingselectorby performing the following steps: Find an element matchingselector.Clockclock()Playwright has ability to mock clock and passage of time.default voidclose()IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed.voidclose(Page.CloseOptions options)IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed.Stringcontent()Gets the full HTML contents of the page, including the doctype.BrowserContextcontext()Get the browser context that the page belongs to.default voiddblclick(String selector)This method double clicks an element matchingselectorby performing the following steps: Find an element matchingselector.voiddblclick(String selector, Page.DblclickOptions options)This method double clicks an element matchingselectorby performing the following steps: Find an element matchingselector.default voiddispatchEvent(String selector, String type)The snippet below dispatches theclickevent on the element.default voiddispatchEvent(String selector, String type, Object eventInit)The snippet below dispatches theclickevent on the element.voiddispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options)The snippet below dispatches theclickevent on the element.default voiddragAndDrop(String source, String target)This method drags the source element to the target element.voiddragAndDrop(String source, String target, Page.DragAndDropOptions options)This method drags the source element to the target element.default voidemulateMedia()This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.voidemulateMedia(Page.EmulateMediaOptions options)This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.default ObjectevalOnSelector(String selector, String expression)The method finds an element matching the specified selector within the page and passes it as a first argument toexpression.default ObjectevalOnSelector(String selector, String expression, Object arg)The method finds an element matching the specified selector within the page and passes it as a first argument toexpression.ObjectevalOnSelector(String selector, String expression, Object arg, Page.EvalOnSelectorOptions options)The method finds an element matching the specified selector within the page and passes it as a first argument toexpression.default ObjectevalOnSelectorAll(String selector, String expression)The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument toexpression.ObjectevalOnSelectorAll(String selector, String expression, Object arg)The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument toexpression.default Objectevaluate(String expression)Returns the value of theexpressioninvocation.Objectevaluate(String expression, Object arg)Returns the value of theexpressioninvocation.default JSHandleevaluateHandle(String expression)Returns the value of theexpressioninvocation as aJSHandle.JSHandleevaluateHandle(String expression, Object arg)Returns the value of theexpressioninvocation as aJSHandle.default voidexposeBinding(String name, BindingCallback callback)The method adds a function callednameon thewindowobject of every frame in this page.voidexposeBinding(String name, BindingCallback callback, Page.ExposeBindingOptions options)The method adds a function callednameon thewindowobject of every frame in this page.voidexposeFunction(String name, FunctionCallback callback)The method adds a function callednameon thewindowobject of every frame in the page.default voidfill(String selector, String value)This method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent after filling.voidfill(String selector, String value, Page.FillOptions options)This method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent after filling.default voidfocus(String selector)This method fetches an element withselectorand focuses it.voidfocus(String selector, Page.FocusOptions options)This method fetches an element withselectorand focuses it.Frameframe(String name)Returns frame matching the specified criteria.FrameframeByUrl(String url)Returns frame with matching URL.FrameframeByUrl(Predicate<String> url)Returns frame with matching URL.FrameframeByUrl(Pattern url)Returns frame with matching URL.FrameLocatorframeLocator(String selector)When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.List<Frame>frames()An array of all frames attached to the page.default StringgetAttribute(String selector, String name)Returns element attribute value.StringgetAttribute(String selector, String name, Page.GetAttributeOptions options)Returns element attribute value.default LocatorgetByAltText(String text)Allows locating elements by their alt text.LocatorgetByAltText(String text, Page.GetByAltTextOptions options)Allows locating elements by their alt text.default LocatorgetByAltText(Pattern text)Allows locating elements by their alt text.LocatorgetByAltText(Pattern text, Page.GetByAltTextOptions options)Allows locating elements by their alt text.default LocatorgetByLabel(String text)Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.LocatorgetByLabel(String text, Page.GetByLabelOptions options)Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.default LocatorgetByLabel(Pattern text)Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.LocatorgetByLabel(Pattern text, Page.GetByLabelOptions options)Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.default LocatorgetByPlaceholder(String text)Allows locating input elements by the placeholder text.LocatorgetByPlaceholder(String text, Page.GetByPlaceholderOptions options)Allows locating input elements by the placeholder text.default LocatorgetByPlaceholder(Pattern text)Allows locating input elements by the placeholder text.LocatorgetByPlaceholder(Pattern text, Page.GetByPlaceholderOptions options)Allows locating input elements by the placeholder text.default LocatorgetByRole(AriaRole role)LocatorgetByRole(AriaRole role, Page.GetByRoleOptions options)LocatorgetByTestId(String testId)Locate element by the test id.LocatorgetByTestId(Pattern testId)Locate element by the test id.default LocatorgetByText(String text)Allows locating elements that contain given text.LocatorgetByText(String text, Page.GetByTextOptions options)Allows locating elements that contain given text.default LocatorgetByText(Pattern text)Allows locating elements that contain given text.LocatorgetByText(Pattern text, Page.GetByTextOptions options)Allows locating elements that contain given text.default LocatorgetByTitle(String text)Allows locating elements by their title attribute.LocatorgetByTitle(String text, Page.GetByTitleOptions options)Allows locating elements by their title attribute.default LocatorgetByTitle(Pattern text)Allows locating elements by their title attribute.LocatorgetByTitle(Pattern text, Page.GetByTitleOptions options)Allows locating elements by their title attribute.default ResponsegoBack()Returns the main resource response.ResponsegoBack(Page.GoBackOptions options)Returns the main resource response.default ResponsegoForward()Returns the main resource response.ResponsegoForward(Page.GoForwardOptions options)Returns the main resource response.default voidhover(String selector)This method hovers over an element matchingselectorby performing the following steps: Find an element matchingselector.voidhover(String selector, Page.HoverOptions options)This method hovers over an element matchingselectorby performing the following steps: Find an element matchingselector.default StringinnerHTML(String selector)Returnselement.innerHTML.StringinnerHTML(String selector, Page.InnerHTMLOptions options)Returnselement.innerHTML.default StringinnerText(String selector)Returnselement.innerText.StringinnerText(String selector, Page.InnerTextOptions options)Returnselement.innerText.default StringinputValue(String selector)Returnsinput.valuefor the selected<input>or<textarea>or<select>element.StringinputValue(String selector, Page.InputValueOptions options)Returnsinput.valuefor the selected<input>or<textarea>or<select>element.default booleanisChecked(String selector)Returns whether the element is checked.booleanisChecked(String selector, Page.IsCheckedOptions options)Returns whether the element is checked.booleanisClosed()Indicates that the page has been closed.default booleanisDisabled(String selector)Returns whether the element is disabled, the opposite of enabled.booleanisDisabled(String selector, Page.IsDisabledOptions options)Returns whether the element is disabled, the opposite of enabled.default booleanisEditable(String selector)Returns whether the element is editable.booleanisEditable(String selector, Page.IsEditableOptions options)Returns whether the element is editable.default booleanisEnabled(String selector)Returns whether the element is enabled.booleanisEnabled(String selector, Page.IsEnabledOptions options)Returns whether the element is enabled.default booleanisHidden(String selector)Returns whether the element is hidden, the opposite of visible.booleanisHidden(String selector, Page.IsHiddenOptions options)Returns whether the element is hidden, the opposite of visible.default booleanisVisible(String selector)Returns whether the element is visible.booleanisVisible(String selector, Page.IsVisibleOptions options)Returns whether the element is visible.Keyboardkeyboard()default Locatorlocator(String selector)The method returns an element locator that can be used to perform actions on this page / frame.Locatorlocator(String selector, Page.LocatorOptions options)The method returns an element locator that can be used to perform actions on this page / frame.FramemainFrame()The page's main frame.Mousemouse()default Responsenavigate(String url)Returns the main resource response.Responsenavigate(String url, Page.NavigateOptions options)Returns the main resource response.voidoffClose(Consumer<Page> handler)Removes handler that was previously added withonClose(handler).voidoffConsoleMessage(Consumer<ConsoleMessage> handler)Removes handler that was previously added withonConsoleMessage(handler).voidoffCrash(Consumer<Page> handler)Removes handler that was previously added withonCrash(handler).voidoffDialog(Consumer<Dialog> handler)Removes 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).voidoffLoad(Consumer<Page> handler)Removes handler that was previously added withonLoad(handler).voidoffPageError(Consumer<String> handler)Removes handler that was previously added withonPageError(handler).voidoffPopup(Consumer<Page> handler)Removes 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).voidoffWorker(Consumer<Worker> handler)Removes handler that was previously added withonWorker(handler).voidonceDialog(Consumer<Dialog> handler)Adds one-offDialoghandler.voidonClose(Consumer<Page> handler)Emitted when the page closes.voidonConsoleMessage(Consumer<ConsoleMessage> handler)Emitted when JavaScript within the page calls one of console API methods, e.g.voidonCrash(Consumer<Page> handler)Emitted when the page crashes.voidonDialog(Consumer<Dialog> handler)Emitted 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.voidonLoad(Consumer<Page> handler)Emitted when the JavaScriptloadevent is dispatched.voidonPageError(Consumer<String> handler)Emitted when an uncaught exception happens within the page.voidonPopup(Consumer<Page> handler)Emitted when the page opens a new tab or window.voidonRequest(Consumer<Request> handler)Emitted 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.voidonWorker(Consumer<Worker> handler)Emitted when a dedicated WebWorker is spawned by the page.Pageopener()Returns the opener for popup pages andnullfor others.voidpause()Pauses script execution.default byte[]pdf()Returns the PDF buffer.byte[]pdf(Page.PdfOptions options)Returns the PDF buffer.default voidpress(String selector, String key)Focuses the element, and then usesKeyboard.down()andKeyboard.up().voidpress(String selector, String key, Page.PressOptions options)Focuses the element, and then usesKeyboard.down()andKeyboard.up().default ElementHandlequerySelector(String selector)The method finds an element matching the specified selector within the page.ElementHandlequerySelector(String selector, Page.QuerySelectorOptions options)The method finds an element matching the specified selector within the page.List<ElementHandle>querySelectorAll(String selector)The method finds all elements matching the specified selector within the page.default Responsereload()This method reloads the current page, in the same way as if the user had triggered a browser refresh.Responsereload(Page.ReloadOptions options)This method reloads the current page, in the same way as if the user had triggered a browser refresh.voidremoveLocatorHandler(Locator locator)Removes all locator handlers added byPage.addLocatorHandler()for a specific locator.APIRequestContextrequest()API testing helper associated with this page.default voidroute(String url, Consumer<Route> handler)Routing provides the capability to modify network requests that are made by a page.voidroute(String url, Consumer<Route> handler, Page.RouteOptions options)Routing provides the capability to modify network requests that are made by a page.default voidroute(Predicate<String> url, Consumer<Route> handler)Routing provides the capability to modify network requests that are made by a page.voidroute(Predicate<String> url, Consumer<Route> handler, Page.RouteOptions options)Routing provides the capability to modify network requests that are made by a page.default voidroute(Pattern url, Consumer<Route> handler)Routing provides the capability to modify network requests that are made by a page.voidroute(Pattern url, Consumer<Route> handler, Page.RouteOptions options)Routing provides the capability to modify network requests that are made by a page.default voidrouteFromHAR(Path har)If specified the network requests that are made in the page will be served from the HAR file.voidrouteFromHAR(Path har, Page.RouteFromHAROptions options)If specified the network requests that are made in the page will be served from the HAR file.default byte[]screenshot()Returns the buffer with the captured screenshot.byte[]screenshot(Page.ScreenshotOptions options)Returns the buffer with the captured screenshot.default List<String>selectOption(String selector, ElementHandle values)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default List<String>selectOption(String selector, ElementHandle[] values)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.List<String>selectOption(String selector, ElementHandle[] values, Page.SelectOptionOptions options)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.List<String>selectOption(String selector, ElementHandle values, Page.SelectOptionOptions options)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default List<String>selectOption(String selector, SelectOption values)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default List<String>selectOption(String selector, SelectOption[] values)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.List<String>selectOption(String selector, SelectOption[] values, Page.SelectOptionOptions options)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.List<String>selectOption(String selector, SelectOption values, Page.SelectOptionOptions options)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default List<String>selectOption(String selector, String values)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default List<String>selectOption(String selector, String[] values)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.List<String>selectOption(String selector, String[] values, Page.SelectOptionOptions options)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.List<String>selectOption(String selector, String values, Page.SelectOptionOptions options)This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.default voidsetChecked(String selector, boolean checked)This method checks or unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.voidsetChecked(String selector, boolean checked, Page.SetCheckedOptions options)This method checks or unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidsetContent(String html)This method internally calls document.write(), inheriting all its specific characteristics and behaviors.voidsetContent(String html, Page.SetContentOptions options)This method internally calls document.write(), inheriting all its specific characteristics and behaviors.voidsetDefaultNavigationTimeout(double timeout)This setting will change the default maximum navigation time for the following methods and related shortcuts:Page.goBack()Page.goForward()Page.navigate()Page.reload()Page.setContent()Page.waitForNavigation()Page.waitForURL()voidsetDefaultTimeout(double timeout)This setting will change the default maximum time for all the methods acceptingtimeoutoption.voidsetExtraHTTPHeaders(Map<String,String> headers)The extra HTTP headers will be sent with every request the page initiates.default voidsetInputFiles(String selector, FilePayload files)Sets the value of the file input to these file paths or files.default voidsetInputFiles(String selector, FilePayload[] files)Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, FilePayload[] files, Page.SetInputFilesOptions options)Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, FilePayload files, Page.SetInputFilesOptions options)Sets the value of the file input to these file paths or files.default voidsetInputFiles(String selector, Path files)Sets the value of the file input to these file paths or files.default voidsetInputFiles(String selector, Path[] files)Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, Path[] files, Page.SetInputFilesOptions options)Sets the value of the file input to these file paths or files.voidsetInputFiles(String selector, Path files, Page.SetInputFilesOptions options)Sets the value of the file input to these file paths or files.voidsetViewportSize(int width, int height)In the case of multiple pages in a single browser, each page can have its own viewport size.default voidtap(String selector)This method taps an element matchingselectorby performing the following steps: Find an element matchingselector.voidtap(String selector, Page.TapOptions options)This method taps an element matchingselectorby performing the following steps: Find an element matchingselector.default StringtextContent(String selector)Returnselement.textContent.StringtextContent(String selector, Page.TextContentOptions options)Returnselement.textContent.Stringtitle()Returns the page's title.Touchscreentouchscreen()default voidtype(String selector, String text)Deprecated.In most cases, you should useLocator.fill()instead.voidtype(String selector, String text, Page.TypeOptions options)Deprecated.In most cases, you should useLocator.fill()instead.default voiduncheck(String selector)This method unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.voiduncheck(String selector, Page.UncheckOptions options)This method unchecks an element matchingselectorby performing the following steps: Find an element matchingselector.default voidunroute(String url)Removes a route created withPage.route().voidunroute(String url, Consumer<Route> handler)Removes a route created withPage.route().default voidunroute(Predicate<String> url)Removes a route created withPage.route().voidunroute(Predicate<String> url, Consumer<Route> handler)Removes a route created withPage.route().default voidunroute(Pattern url)Removes a route created withPage.route().voidunroute(Pattern url, Consumer<Route> handler)Removes a route created withPage.route().voidunrouteAll()Removes all routes created withPage.route()andPage.routeFromHAR().Stringurl()Videovideo()Video object associated with this page.ViewportSizeviewportSize()PagewaitForClose(Page.WaitForCloseOptions options, Runnable callback)Performs action and waits for the Page to close.default PagewaitForClose(Runnable callback)Performs action and waits for the Page to close.default voidwaitForCondition(BooleanSupplier condition)The method will block until the condition returns true.voidwaitForCondition(BooleanSupplier condition, Page.WaitForConditionOptions options)The method will block until the condition returns true.ConsoleMessagewaitForConsoleMessage(Page.WaitForConsoleMessageOptions options, Runnable callback)Performs action and waits for aConsoleMessageto be logged by in the page.default ConsoleMessagewaitForConsoleMessage(Runnable callback)Performs action and waits for aConsoleMessageto be logged by in the page.DownloadwaitForDownload(Page.WaitForDownloadOptions options, Runnable callback)Performs action and waits for a newDownload.default DownloadwaitForDownload(Runnable callback)Performs action and waits for a newDownload.FileChooserwaitForFileChooser(Page.WaitForFileChooserOptions options, Runnable callback)Performs action and waits for a newFileChooserto be created.default FileChooserwaitForFileChooser(Runnable callback)Performs action and waits for a newFileChooserto be created.default JSHandlewaitForFunction(String expression)Returns when theexpressionreturns a truthy value.default JSHandlewaitForFunction(String expression, Object arg)Returns when theexpressionreturns a truthy value.JSHandlewaitForFunction(String expression, Object arg, Page.WaitForFunctionOptions options)Returns when theexpressionreturns a truthy value.default voidwaitForLoadState()Returns when the required load state has been reached.default voidwaitForLoadState(LoadState state)Returns when the required load state has been reached.voidwaitForLoadState(LoadState state, Page.WaitForLoadStateOptions options)Returns when the required load state has been reached.ResponsewaitForNavigation(Page.WaitForNavigationOptions options, Runnable callback)Deprecated.This method is inherently racy, please usePage.waitForURL()instead.default ResponsewaitForNavigation(Runnable callback)Deprecated.This method is inherently racy, please usePage.waitForURL()instead.PagewaitForPopup(Page.WaitForPopupOptions options, Runnable callback)Performs action and waits for a popupPage.default PagewaitForPopup(Runnable callback)Performs action and waits for a popupPage.RequestwaitForRequest(String urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)Waits for the matching request and returns it.default RequestwaitForRequest(String urlOrPredicate, Runnable callback)Waits for the matching request and returns it.RequestwaitForRequest(Predicate<Request> urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)Waits for the matching request and returns it.default RequestwaitForRequest(Predicate<Request> urlOrPredicate, Runnable callback)Waits for the matching request and returns it.RequestwaitForRequest(Pattern urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)Waits for the matching request and returns it.default RequestwaitForRequest(Pattern urlOrPredicate, Runnable callback)Waits for the matching request and returns it.RequestwaitForRequestFinished(Page.WaitForRequestFinishedOptions options, Runnable callback)Performs action and waits for aRequestto finish loading.default RequestwaitForRequestFinished(Runnable callback)Performs action and waits for aRequestto finish loading.ResponsewaitForResponse(String urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)Returns the matched response.default ResponsewaitForResponse(String urlOrPredicate, Runnable callback)Returns the matched response.ResponsewaitForResponse(Predicate<Response> urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)Returns the matched response.default ResponsewaitForResponse(Predicate<Response> urlOrPredicate, Runnable callback)Returns the matched response.ResponsewaitForResponse(Pattern urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)Returns the matched response.default ResponsewaitForResponse(Pattern urlOrPredicate, Runnable callback)Returns the matched response.default ElementHandlewaitForSelector(String selector)Returns when element specified by selector satisfiesstateoption.ElementHandlewaitForSelector(String selector, Page.WaitForSelectorOptions options)Returns when element specified by selector satisfiesstateoption.voidwaitForTimeout(double timeout)Waits for the giventimeoutin milliseconds.default voidwaitForURL(String url)Waits for the main frame to navigate to the given URL.voidwaitForURL(String url, Page.WaitForURLOptions options)Waits for the main frame to navigate to the given URL.default voidwaitForURL(Predicate<String> url)Waits for the main frame to navigate to the given URL.voidwaitForURL(Predicate<String> url, Page.WaitForURLOptions options)Waits for the main frame to navigate to the given URL.default voidwaitForURL(Pattern url)Waits for the main frame to navigate to the given URL.voidwaitForURL(Pattern url, Page.WaitForURLOptions options)Waits for the main frame to navigate to the given URL.WebSocketwaitForWebSocket(Page.WaitForWebSocketOptions options, Runnable callback)Performs action and waits for a newWebSocket.default WebSocketwaitForWebSocket(Runnable callback)Performs action and waits for a newWebSocket.WorkerwaitForWorker(Page.WaitForWorkerOptions options, Runnable callback)Performs action and waits for a newWorker.default WorkerwaitForWorker(Runnable callback)Performs action and waits for a newWorker.List<Worker>workers()This method returns all of the dedicated WebWorkers associated with the page.
-
-
-
Method Detail
-
offClose
void offClose(Consumer<Page> handler)
Removes handler that was previously added withonClose(handler).
-
onConsoleMessage
void onConsoleMessage(Consumer<ConsoleMessage> handler)
Emitted when JavaScript within the page calls one of console API methods, e.g.console.logorconsole.dir.The arguments passed into
console.logare available on theConsoleMessageevent handler argument.Usage
page.onConsoleMessage(msg -> { for (int i = 0; i < msg.args().size(); ++i) System.out.println(i + ": " + msg.args().get(i).jsonValue()); }); page.evaluate("() => console.log('hello', 5, { foo: 'bar' })");
-
offConsoleMessage
void offConsoleMessage(Consumer<ConsoleMessage> handler)
Removes handler that was previously added withonConsoleMessage(handler).
-
onCrash
void onCrash(Consumer<Page> handler)
Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.The most common way to deal with crashes is to catch an exception:
try { // Crash might happen during a click. page.click("button"); // Or while waiting for an event. page.waitForPopup(() -> {}); } catch (PlaywrightException e) { // When the page crashes, exception message contains "crash". }
-
offCrash
void offCrash(Consumer<Page> handler)
Removes handler that was previously added withonCrash(handler).
-
onDialog
void onDialog(Consumer<Dialog> handler)
Emitted when a JavaScript dialog appears, such asalert,prompt,confirmorbeforeunload. Listener **must** eitherDialog.accept()orDialog.dismiss()the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.Usage
page.onDialog(dialog -> { dialog.accept(); });NOTE: When no
Page.onDialog()orBrowserContext.onDialog()listeners are present, all dialogs are automatically dismissed.
-
offDialog
void offDialog(Consumer<Dialog> handler)
Removes handler that was previously added withonDialog(handler).
-
onDOMContentLoaded
void onDOMContentLoaded(Consumer<Page> handler)
Emitted when the JavaScriptDOMContentLoadedevent is dispatched.
-
offDOMContentLoaded
void offDOMContentLoaded(Consumer<Page> handler)
Removes handler that was previously added withonDOMContentLoaded(handler).
-
onDownload
void onDownload(Consumer<Download> handler)
Emitted when attachment download started. User can access basic file operations on downloaded content via the passedDownloadinstance.
-
offDownload
void offDownload(Consumer<Download> handler)
Removes handler that was previously added withonDownload(handler).
-
onFileChooser
void onFileChooser(Consumer<FileChooser> handler)
Emitted when a file chooser is supposed to appear, such as after clicking the<input type=file>. Playwright can respond to it via setting the input files usingFileChooser.setFiles()that can be uploaded after that.page.onFileChooser(fileChooser -> { fileChooser.setFiles(Paths.get("/tmp/myfile.pdf")); });
-
offFileChooser
void offFileChooser(Consumer<FileChooser> handler)
Removes handler that was previously added withonFileChooser(handler).
-
offFrameAttached
void offFrameAttached(Consumer<Frame> handler)
Removes handler that was previously added withonFrameAttached(handler).
-
offFrameDetached
void offFrameDetached(Consumer<Frame> handler)
Removes handler that was previously added withonFrameDetached(handler).
-
onFrameNavigated
void onFrameNavigated(Consumer<Frame> handler)
Emitted when a frame is navigated to a new url.
-
offFrameNavigated
void offFrameNavigated(Consumer<Frame> handler)
Removes handler that was previously added withonFrameNavigated(handler).
-
offLoad
void offLoad(Consumer<Page> handler)
Removes handler that was previously added withonLoad(handler).
-
onPageError
void onPageError(Consumer<String> handler)
Emitted when an uncaught exception happens within the page.// Log all uncaught errors to the terminal page.onPageError(exception -> { System.out.println("Uncaught exception: " + exception); }); // Navigate to a page with an exception. page.navigate("data:text/html,<script>throw new Error('Test')</script>");
-
offPageError
void offPageError(Consumer<String> handler)
Removes handler that was previously added withonPageError(handler).
-
onPopup
void onPopup(Consumer<Page> handler)
Emitted when the page opens a new tab or window. This event is emitted in addition to theBrowserContext.onPage(), but only for popups relevant to this page.The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with
window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup. If you would like to route/listen to this network request, useBrowserContext.route()andBrowserContext.onRequest()respectively instead of similar methods on thePage.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
void offPopup(Consumer<Page> handler)
Removes handler that was previously added withonPopup(handler).
-
onRequest
void onRequest(Consumer<Request> handler)
Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, seePage.route()orBrowserContext.route().
-
offRequest
void offRequest(Consumer<Request> handler)
Removes handler that was previously added withonRequest(handler).
-
onRequestFailed
void onRequestFailed(Consumer<Request> handler)
Emitted when a request fails, for example by timing out.page.onRequestFailed(request -> { System.out.println(request.url() + " " + request.failure()); });NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with
Page.onRequestFinished()event and not withPage.onRequestFailed(). A request will only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error net::ERR_FAILED.
-
offRequestFailed
void offRequestFailed(Consumer<Request> handler)
Removes handler that was previously added withonRequestFailed(handler).
-
onRequestFinished
void onRequestFinished(Consumer<Request> handler)
Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events isrequest,responseandrequestfinished.
-
offRequestFinished
void offRequestFinished(Consumer<Request> handler)
Removes handler that was previously added withonRequestFinished(handler).
-
onResponse
void onResponse(Consumer<Response> handler)
Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events isrequest,responseandrequestfinished.
-
offResponse
void offResponse(Consumer<Response> handler)
Removes handler that was previously added withonResponse(handler).
-
offWebSocket
void offWebSocket(Consumer<WebSocket> handler)
Removes handler that was previously added withonWebSocket(handler).
-
onWorker
void onWorker(Consumer<Worker> handler)
Emitted when a dedicated WebWorker is spawned by the page.
-
offWorker
void offWorker(Consumer<Worker> handler)
Removes handler that was previously added withonWorker(handler).
-
clock
Clock clock()
Playwright has ability to mock clock and passage of time.- Since:
- v1.45
-
addInitScript
void addInitScript(String script)
Adds a script which would be evaluated in one of the following scenarios:- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed
Math.random.Usage
An example of overriding
Math.randombefore the page loads:// In your playwright script, assuming the preload.js file is in same directory page.addInitScript(Paths.get("./preload.js"));NOTE: The order of evaluation of multiple scripts installed via
BrowserContext.addInitScript()andPage.addInitScript()is not defined.- Parameters:
script- Script to be evaluated in all pages in the browser context.- Since:
- v1.8
-
addInitScript
void addInitScript(Path script)
Adds a script which would be evaluated in one of the following scenarios:- Whenever the page is navigated.
- Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed
Math.random.Usage
An example of overriding
Math.randombefore the page loads:// In your playwright script, assuming the preload.js file is in same directory page.addInitScript(Paths.get("./preload.js"));NOTE: The order of evaluation of multiple scripts installed via
BrowserContext.addInitScript()andPage.addInitScript()is not defined.- Parameters:
script- Script to be evaluated in all pages in the browser context.- Since:
- v1.8
-
addScriptTag
default ElementHandle addScriptTag()
Adds a<script>tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.- Since:
- v1.8
-
addScriptTag
ElementHandle addScriptTag(Page.AddScriptTagOptions options)
Adds a<script>tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.- Since:
- v1.8
-
addStyleTag
default ElementHandle addStyleTag()
Adds a<link rel="stylesheet">tag into the page with the desired url or a<style type="text/css">tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.- Since:
- v1.8
-
addStyleTag
ElementHandle addStyleTag(Page.AddStyleTagOptions options)
Adds a<link rel="stylesheet">tag into the page with the desired url or a<style type="text/css">tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.- Since:
- v1.8
-
bringToFront
void bringToFront()
Brings page to front (activates tab).- Since:
- v1.8
-
check
default void check(String selector)
This method checks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
check
void check(String selector, Page.CheckOptions options)
This method checks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already checked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
click
default void click(String selector)
This method clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
click
void click(String selector, Page.ClickOptions options)
This method clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
close
default void close()
IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed. IfrunBeforeUnloadistruethe method will run unload handlers, but will **not** wait for the page to close.By default,
page.close()**does not** runbeforeunloadhandlers.NOTE: if
runBeforeUnloadis passed as true, abeforeunloaddialog might be summoned and should be handled manually viaPage.onDialog()event.- Specified by:
closein interfaceAutoCloseable- Since:
- v1.8
-
close
void close(Page.CloseOptions options)
IfrunBeforeUnloadisfalse, does not run any unload handlers and waits for the page to be closed. IfrunBeforeUnloadistruethe method will run unload handlers, but will **not** wait for the page to close.By default,
page.close()**does not** runbeforeunloadhandlers.NOTE: if
runBeforeUnloadis passed as true, abeforeunloaddialog might be summoned and should be handled manually viaPage.onDialog()event.- Since:
- v1.8
-
content
String content()
Gets the full HTML contents of the page, including the doctype.- Since:
- v1.8
-
context
BrowserContext context()
Get the browser context that the page belongs to.- Since:
- v1.8
-
dblclick
default void dblclick(String selector)
This method double clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to double click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. Note that if the first click of thedblclick()triggers a navigation event, this method will throw.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
page.dblclick()dispatches twoclickevents and a singledblclickevent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
dblclick
void dblclick(String selector, Page.DblclickOptions options)
This method double clicks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to double click in the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. Note that if the first click of thedblclick()triggers a navigation event, this method will throw.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
page.dblclick()dispatches twoclickevents and a singledblclickevent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
dispatchEvent
default void dispatchEvent(String selector, String type, Object eventInit)
The snippet below dispatches theclickevent on the element. Regardless of the visibility state of the element,clickis dispatched. This is equivalent to calling element.click().Usage
page.dispatchEvent("button#submit", "click");Under the hood, it creates an instance of an event based on the given
type, initializes it witheventInitproperties and dispatches it on the element. Events arecomposed,cancelableand bubble by default.Since
eventInitis event-specific, please refer to the events documentation for the lists of initial properties:- DeviceMotionEvent
- DeviceOrientationEvent
- DragEvent
- Event
- FocusEvent
- KeyboardEvent
- MouseEvent
- PointerEvent
- TouchEvent
- WheelEvent
You can also specify
JSHandleas the property value if you want live objects to be passed into the event:// Note you can only create DataTransfer in Chromium and Firefox JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()"); Map<String, Object> arg = new HashMap<>(); arg.put("dataTransfer", dataTransfer); page.dispatchEvent("#source", "dragstart", arg);- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.type- DOM event type:"click","dragstart", etc.eventInit- Optional event-specific initialization properties.- Since:
- v1.8
-
dispatchEvent
default void dispatchEvent(String selector, String type)
The snippet below dispatches theclickevent on the element. Regardless of the visibility state of the element,clickis dispatched. This is equivalent to calling element.click().Usage
page.dispatchEvent("button#submit", "click");Under the hood, it creates an instance of an event based on the given
type, initializes it witheventInitproperties and dispatches it on the element. Events arecomposed,cancelableand bubble by default.Since
eventInitis event-specific, please refer to the events documentation for the lists of initial properties:- DeviceMotionEvent
- DeviceOrientationEvent
- DragEvent
- Event
- FocusEvent
- KeyboardEvent
- MouseEvent
- PointerEvent
- TouchEvent
- WheelEvent
You can also specify
JSHandleas the property value if you want live objects to be passed into the event:// Note you can only create DataTransfer in Chromium and Firefox JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()"); Map<String, Object> arg = new HashMap<>(); arg.put("dataTransfer", dataTransfer); page.dispatchEvent("#source", "dragstart", arg);- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.type- DOM event type:"click","dragstart", etc.- Since:
- v1.8
-
dispatchEvent
void dispatchEvent(String selector, String type, Object eventInit, Page.DispatchEventOptions options)
The snippet below dispatches theclickevent on the element. Regardless of the visibility state of the element,clickis dispatched. This is equivalent to calling element.click().Usage
page.dispatchEvent("button#submit", "click");Under the hood, it creates an instance of an event based on the given
type, initializes it witheventInitproperties and dispatches it on the element. Events arecomposed,cancelableand bubble by default.Since
eventInitis event-specific, please refer to the events documentation for the lists of initial properties:- DeviceMotionEvent
- DeviceOrientationEvent
- DragEvent
- Event
- FocusEvent
- KeyboardEvent
- MouseEvent
- PointerEvent
- TouchEvent
- WheelEvent
You can also specify
JSHandleas the property value if you want live objects to be passed into the event:// Note you can only create DataTransfer in Chromium and Firefox JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()"); Map<String, Object> arg = new HashMap<>(); arg.put("dataTransfer", dataTransfer); page.dispatchEvent("#source", "dragstart", arg);- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.type- DOM event type:"click","dragstart", etc.eventInit- Optional event-specific initialization properties.- Since:
- v1.8
-
dragAndDrop
default void dragAndDrop(String source, String target)
This method drags the source element to the target element. It will first move to the source element, perform amousedown, then move to the target element and perform amouseup.Usage
page.dragAndDrop("#source", '#target'); // or specify exact positions relative to the top-left corners of the elements: page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions() .setSourcePosition(34, 7).setTargetPosition(10, 20));- Parameters:
source- A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.target- A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
dragAndDrop
void dragAndDrop(String source, String target, Page.DragAndDropOptions options)
This method drags the source element to the target element. It will first move to the source element, perform amousedown, then move to the target element and perform amouseup.Usage
page.dragAndDrop("#source", '#target'); // or specify exact positions relative to the top-left corners of the elements: page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions() .setSourcePosition(34, 7).setTargetPosition(10, 20));- Parameters:
source- A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.target- A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
emulateMedia
default void emulateMedia()
This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.Usage
page.evaluate("() => matchMedia('screen').matches"); // → true page.evaluate("() => matchMedia('print').matches"); // → false page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT)); page.evaluate("() => matchMedia('screen').matches"); // → false page.evaluate("() => matchMedia('print').matches"); // → true page.emulateMedia(new Page.EmulateMediaOptions()); page.evaluate("() => matchMedia('screen').matches"); // → true page.evaluate("() => matchMedia('print').matches"); // → falsepage.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK)); page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches"); // → true page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches"); // → false page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches"); // → false- Since:
- v1.8
-
emulateMedia
void emulateMedia(Page.EmulateMediaOptions options)
This method changes theCSS media typethrough themediaargument, and/or the"prefers-colors-scheme"media feature, using thecolorSchemeargument.Usage
page.evaluate("() => matchMedia('screen').matches"); // → true page.evaluate("() => matchMedia('print').matches"); // → false page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.PRINT)); page.evaluate("() => matchMedia('screen').matches"); // → false page.evaluate("() => matchMedia('print').matches"); // → true page.emulateMedia(new Page.EmulateMediaOptions()); page.evaluate("() => matchMedia('screen').matches"); // → true page.evaluate("() => matchMedia('print').matches"); // → falsepage.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK)); page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches"); // → true page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches"); // → false page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches"); // → false- Since:
- v1.8
-
evalOnSelector
default Object evalOnSelector(String selector, String expression, Object arg)
The method finds an element matching the specified selector within the page and passes it as a first argument toexpression. If no elements match the selector, the method throws an error. Returns the value ofexpression.If
expressionreturns a Promise, thenPage.evalOnSelector()would wait for the promise to resolve and return its value.Usage
String searchValue = (String) page.evalOnSelector("#search", "el => el.value"); String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href"); String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.9
-
evalOnSelector
default Object evalOnSelector(String selector, String expression)
The method finds an element matching the specified selector within the page and passes it as a first argument toexpression. If no elements match the selector, the method throws an error. Returns the value ofexpression.If
expressionreturns a Promise, thenPage.evalOnSelector()would wait for the promise to resolve and return its value.Usage
String searchValue = (String) page.evalOnSelector("#search", "el => el.value"); String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href"); String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.9
-
evalOnSelector
Object evalOnSelector(String selector, String expression, Object arg, Page.EvalOnSelectorOptions options)
The method finds an element matching the specified selector within the page and passes it as a first argument toexpression. If no elements match the selector, the method throws an error. Returns the value ofexpression.If
expressionreturns a Promise, thenPage.evalOnSelector()would wait for the promise to resolve and return its value.Usage
String searchValue = (String) page.evalOnSelector("#search", "el => el.value"); String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href"); String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.9
-
evalOnSelectorAll
default Object evalOnSelectorAll(String selector, String expression)
The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument toexpression. Returns the result ofexpressioninvocation.If
expressionreturns a Promise, thenPage.evalOnSelectorAll()would wait for the promise to resolve and return its value.Usage
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.9
-
evalOnSelectorAll
Object evalOnSelectorAll(String selector, String expression, Object arg)
The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument toexpression. Returns the result ofexpressioninvocation.If
expressionreturns a Promise, thenPage.evalOnSelectorAll()would wait for the promise to resolve and return its value.Usage
boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);- Parameters:
selector- A selector to query for.expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.9
-
evaluate
default Object evaluate(String expression)
Returns the value of theexpressioninvocation.If the function passed to the
Page.evaluate()returns a Promise, thenPage.evaluate()would wait for the promise to resolve and return its value.If the function passed to the
Page.evaluate()returns a non-[Serializable] value, thenPage.evaluate()resolves toundefined. Playwright also supports transferring some additional values that are not serializable byJSON:-0,NaN,Infinity,-Infinity.Usage
Passing argument to
expression:Object result = page.evaluate("([x, y]) => {\n" + " return Promise.resolve(x * y);\n" + "}", Arrays.asList(7, 8)); System.out.println(result); // prints "56"A string can also be passed in instead of a function:
System.out.println(page.evaluate("1 + 2")); // prints "3"ElementHandleinstances can be passed as an argument to thePage.evaluate():ElementHandle bodyHandle = page.evaluate("document.body"); String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello")); bodyHandle.dispose();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.8
-
evaluate
Object evaluate(String expression, Object arg)
Returns the value of theexpressioninvocation.If the function passed to the
Page.evaluate()returns a Promise, thenPage.evaluate()would wait for the promise to resolve and return its value.If the function passed to the
Page.evaluate()returns a non-[Serializable] value, thenPage.evaluate()resolves toundefined. Playwright also supports transferring some additional values that are not serializable byJSON:-0,NaN,Infinity,-Infinity.Usage
Passing argument to
expression:Object result = page.evaluate("([x, y]) => {\n" + " return Promise.resolve(x * y);\n" + "}", Arrays.asList(7, 8)); System.out.println(result); // prints "56"A string can also be passed in instead of a function:
System.out.println(page.evaluate("1 + 2")); // prints "3"ElementHandleinstances can be passed as an argument to thePage.evaluate():ElementHandle bodyHandle = page.evaluate("document.body"); String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello")); bodyHandle.dispose();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
evaluateHandle
default JSHandle evaluateHandle(String expression)
Returns the value of theexpressioninvocation as aJSHandle.The only difference between
Page.evaluate()andPage.evaluateHandle()is thatPage.evaluateHandle()returnsJSHandle.If the function passed to the
Page.evaluateHandle()returns a Promise, thenPage.evaluateHandle()would wait for the promise to resolve and return its value.Usage
// Handle for the window object. JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)");A string can also be passed in instead of a function:
JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document".JSHandleinstances can be passed as an argument to thePage.evaluateHandle():JSHandle aHandle = page.evaluateHandle("() => document.body"); JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello")); System.out.println(resultHandle.jsonValue()); resultHandle.dispose();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.8
-
evaluateHandle
JSHandle evaluateHandle(String expression, Object arg)
Returns the value of theexpressioninvocation as aJSHandle.The only difference between
Page.evaluate()andPage.evaluateHandle()is thatPage.evaluateHandle()returnsJSHandle.If the function passed to the
Page.evaluateHandle()returns a Promise, thenPage.evaluateHandle()would wait for the promise to resolve and return its value.Usage
// Handle for the window object. JSHandle aWindowHandle = page.evaluateHandle("() => Promise.resolve(window)");A string can also be passed in instead of a function:
JSHandle aHandle = page.evaluateHandle("document"); // Handle for the "document".JSHandleinstances can be passed as an argument to thePage.evaluateHandle():JSHandle aHandle = page.evaluateHandle("() => document.body"); JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello")); System.out.println(resultHandle.jsonValue()); resultHandle.dispose();- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
exposeBinding
default void exposeBinding(String name, BindingCallback callback)
The method adds a function callednameon thewindowobject of every frame in this page. When called, the function executescallbackand returns a Promise which resolves to the return value ofcallback. If thecallbackreturns a Promise, it will be awaited.The first argument of the
callbackfunction contains information about the caller:{ browserContext: BrowserContext, page: Page, frame: Frame }.See
BrowserContext.exposeBinding()for the context-wide version.NOTE: Functions installed via
Page.exposeBinding()survive navigations.Usage
An example of exposing page URL to all frames in a page:
import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch({ headless: false }); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.exposeBinding("pageURL", (source, args) -> source.page().url()); page.setContent("<script>\n" + " async function onClick() {\n" + " document.querySelector('div').textContent = await window.pageURL();\n" + " }\n" + "</script>\n" + "<button onclick=\"onClick()\">Click me</button>\n" + "<div></div>"); page.click("button"); } } }- Parameters:
name- Name of the function on the window object.callback- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
exposeBinding
void exposeBinding(String name, BindingCallback callback, Page.ExposeBindingOptions options)
The method adds a function callednameon thewindowobject of every frame in this page. When called, the function executescallbackand returns a Promise which resolves to the return value ofcallback. If thecallbackreturns a Promise, it will be awaited.The first argument of the
callbackfunction contains information about the caller:{ browserContext: BrowserContext, page: Page, frame: Frame }.See
BrowserContext.exposeBinding()for the context-wide version.NOTE: Functions installed via
Page.exposeBinding()survive navigations.Usage
An example of exposing page URL to all frames in a page:
import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch({ headless: false }); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.exposeBinding("pageURL", (source, args) -> source.page().url()); page.setContent("<script>\n" + " async function onClick() {\n" + " document.querySelector('div').textContent = await window.pageURL();\n" + " }\n" + "</script>\n" + "<button onclick=\"onClick()\">Click me</button>\n" + "<div></div>"); page.click("button"); } } }- Parameters:
name- Name of the function on the window object.callback- Callback function that will be called in the Playwright's context.- Since:
- v1.8
-
exposeFunction
void exposeFunction(String name, FunctionCallback callback)
The method adds a function callednameon thewindowobject of every frame in the page. When called, the function executescallbackand returns a Promise which resolves to the return value ofcallback.If the
callbackreturns a Promise, it will be awaited.See
BrowserContext.exposeFunction()for context-wide exposed function.NOTE: Functions installed via
Page.exposeFunction()survive navigations.Usage
An example of adding a
sha256function to the page:import com.microsoft.playwright.*; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch({ headless: false }); Page page = browser.newPage(); page.exposeFunction("sha256", args -> { String text = (String) args[0]; MessageDigest crypto; try { crypto = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { return null; } byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(token); }); page.setContent("<script>\n" + " async function onClick() {\n" + " document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" + " }\n" + "</script>\n" + "<button onclick=\"onClick()\">Click me</button>\n" + "<div></div>\n"); page.click("button"); } } }- Parameters:
name- Name of the function on the window objectcallback- Callback function which will be called in Playwright's context.- Since:
- v1.8
-
fill
default void fill(String selector, String value)
This method waits for an element matchingselector, waits for actionability checks, focuses the element, fills it and triggers aninputevent after filling. Note that you can pass an empty string to clear the input field.If the target element is not an
<input>,<textarea>or[contenteditable]element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be filled instead.To send fine-grained keyboard events, use
Locator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- Value to fill for the<input>,<textarea>or[contenteditable]element.- Since:
- v1.8
-
fill
void fill(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. Note that you can pass an empty string to clear the input field.If the target element is not an
<input>,<textarea>or[contenteditable]element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be filled instead.To send fine-grained keyboard events, use
Locator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.value- Value to fill for the<input>,<textarea>or[contenteditable]element.- Since:
- v1.8
-
focus
default void focus(String selector)
This method fetches an element withselectorand focuses it. If there's no element matchingselector, the method waits until a matching element appears in the DOM.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
focus
void focus(String selector, Page.FocusOptions options)
This method fetches an element withselectorand focuses it. If there's no element matchingselector, the method waits until a matching element appears in the DOM.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
frame
Frame frame(String name)
Returns frame matching the specified criteria. Eithernameorurlmust be specified.Usage
Frame frame = page.frame("frame-name");Frame frame = page.frameByUrl(Pattern.compile(".*domain.*");- Parameters:
name- Frame name specified in theiframe'snameattribute.- Since:
- v1.8
-
frameByUrl
Frame frameByUrl(String url)
Returns frame with matching URL.- Parameters:
url- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.- Since:
- v1.9
-
frameByUrl
Frame frameByUrl(Pattern url)
Returns frame with matching URL.- Parameters:
url- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.- Since:
- v1.9
-
frameByUrl
Frame frameByUrl(Predicate<String> url)
Returns frame with matching URL.- Parameters:
url- A glob pattern, regex pattern or predicate receiving frame'surlas a [URL] object.- Since:
- v1.9
-
frameLocator
FrameLocator 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.Usage
Following snippet locates element with text "Submit" in the iframe with id
my-frame, like<iframe id="my-frame">:Locator locator = page.frameLocator("#my-iframe").getByText("Submit"); locator.click();- Parameters:
selector- A selector to use when resolving DOM element.- Since:
- v1.17
-
getAttribute
default String getAttribute(String selector, String name)
Returns element attribute value.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.name- Attribute name to get the value for.- Since:
- v1.8
-
getAttribute
String getAttribute(String selector, String name, Page.GetAttributeOptions options)
Returns element attribute value.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.name- Attribute name to get the value for.- Since:
- v1.8
-
getByAltText
default Locator getByAltText(String text)
Allows locating elements by their alt text.Usage
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByAltText
Locator getByAltText(String text, Page.GetByAltTextOptions options)
Allows locating elements by their alt text.Usage
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByAltText
default Locator getByAltText(Pattern text)
Allows locating elements by their alt text.Usage
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByAltText
Locator getByAltText(Pattern text, Page.GetByAltTextOptions options)
Allows locating elements by their alt text.Usage
For example, this method will find the image by alt text "Playwright logo":
page.getByAltText("Playwright logo").click();- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
default Locator getByLabel(String text)
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.Usage
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
Locator getByLabel(String text, Page.GetByLabelOptions options)
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.Usage
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
default Locator getByLabel(Pattern text)
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.Usage
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByLabel
Locator getByLabel(Pattern text, Page.GetByLabelOptions options)
Allows locating input elements by the text of the associated<label>oraria-labelledbyelement, or by thearia-labelattribute.Usage
For example, this method will find inputs by label "Username" and "Password" in the following DOM:
page.getByLabel("Username").fill("john"); page.getByLabel("Password").fill("secret");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
default Locator getByPlaceholder(String text)
Allows locating input elements by the placeholder text.Usage
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
Locator getByPlaceholder(String text, Page.GetByPlaceholderOptions options)
Allows locating input elements by the placeholder text.Usage
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
default Locator getByPlaceholder(Pattern text)
Allows locating input elements by the placeholder text.Usage
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByPlaceholder
Locator getByPlaceholder(Pattern text, Page.GetByPlaceholderOptions options)
Allows locating input elements by the placeholder text.Usage
For example, consider the following DOM structure.
You can fill the input after locating it by the placeholder text:
page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByRole
default Locator getByRole(AriaRole role)
Allows locating elements by their ARIA role, ARIA attributes and accessible name.Usage
Consider the following DOM structure.
You can locate each element by it's implicit role:
assertThat(page .getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Sign up"))) .isVisible(); page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setName("Subscribe")) .check(); page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName( Pattern.compile("submit", Pattern.CASE_INSENSITIVE))) .click();Details
Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting
roleand/oraria-*attributes to default values.- Parameters:
role- Required aria role.- Since:
- v1.27
-
getByRole
Locator getByRole(AriaRole role, Page.GetByRoleOptions options)
Allows locating elements by their ARIA role, ARIA attributes and accessible name.Usage
Consider the following DOM structure.
You can locate each element by it's implicit role:
assertThat(page .getByRole(AriaRole.HEADING, new Page.GetByRoleOptions().setName("Sign up"))) .isVisible(); page.getByRole(AriaRole.CHECKBOX, new Page.GetByRoleOptions().setName("Subscribe")) .check(); page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName( Pattern.compile("submit", Pattern.CASE_INSENSITIVE))) .click();Details
Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.
Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting
roleand/oraria-*attributes to default values.- Parameters:
role- Required aria role.- Since:
- v1.27
-
getByTestId
Locator getByTestId(String testId)
Locate element by the test id.Usage
Consider the following DOM structure.
You can locate the element by it's test id:
page.getByTestId("directions").click();Details
By default, the
data-testidattribute is used as a test id. UseSelectors.setTestIdAttribute()to configure a different test id attribute if necessary.- Parameters:
testId- Id to locate the element by.- Since:
- v1.27
-
getByTestId
Locator getByTestId(Pattern testId)
Locate element by the test id.Usage
Consider the following DOM structure.
You can locate the element by it's test id:
page.getByTestId("directions").click();Details
By default, the
data-testidattribute is used as a test id. UseSelectors.setTestIdAttribute()to configure a different test id attribute if necessary.- Parameters:
testId- Id to locate the element by.- Since:
- v1.27
-
getByText
default Locator getByText(String text)
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.Usage
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))Details
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByText
Locator getByText(String text, Page.GetByTextOptions options)
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.Usage
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))Details
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByText
default Locator getByText(Pattern text)
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.Usage
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))Details
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByText
Locator getByText(Pattern text, Page.GetByTextOptions options)
Allows locating elements that contain given text.See also
Locator.filter()that allows to match by another criteria, like an accessible role, and then filter by the text content.Usage
Consider the following DOM structure:
You can locate by text substring, exact string, or a regular expression:
// Matches <span> page.getByText("world") // Matches first <div> page.getByText("Hello world") // Matches second <div> page.getByText("Hello", new Page.GetByTextOptions().setExact(true)) // Matches both <div>s page.getByText(Pattern.compile("Hello")) // Matches second <div> page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))Details
Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
Input elements of the type
buttonandsubmitare matched by theirvalueinstead of the text content. For example, locating by text"Log in"matches<input type=button value="Log in">.- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
default Locator getByTitle(String text)
Allows locating elements by their title attribute.Usage
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
Locator getByTitle(String text, Page.GetByTitleOptions options)
Allows locating elements by their title attribute.Usage
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
default Locator getByTitle(Pattern text)
Allows locating elements by their title attribute.Usage
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
getByTitle
Locator getByTitle(Pattern text, Page.GetByTitleOptions options)
Allows locating elements by their title attribute.Usage
Consider the following DOM structure.
You can check the issues count after locating it by the title text:
assertThat(page.getByTitle("Issues count")).hasText("25 issues");- Parameters:
text- Text to locate the element for.- Since:
- v1.27
-
goBack
default Response goBack()
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returnsnull.Navigate to the previous page in history.
- Since:
- v1.8
-
goBack
Response goBack(Page.GoBackOptions options)
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returnsnull.Navigate to the previous page in history.
- Since:
- v1.8
-
goForward
default Response goForward()
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returnsnull.Navigate to the next page in history.
- Since:
- v1.8
-
goForward
Response goForward(Page.GoForwardOptions options)
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returnsnull.Navigate to the next page in history.
- Since:
- v1.8
-
navigate
default Response navigate(String url)
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.The method will throw an error if:
- there's an SSL error (e.g. in case of self-signed certificates).
- target URL is invalid.
- the
timeoutis exceeded during navigation. - the remote server does not respond or is unreachable.
- the main resource failed to load.
The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
Response.status().NOTE: The method either throws an error or returns a main resource response. The only exceptions are navigation to
about:blankor navigation to the same URL with a different hash, which would succeed and returnnull.NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.
- Parameters:
url- URL to navigate page to. The url should include scheme, e.g.https://. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.- Since:
- v1.8
-
navigate
Response navigate(String url, Page.NavigateOptions options)
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.The method will throw an error if:
- there's an SSL error (e.g. in case of self-signed certificates).
- target URL is invalid.
- the
timeoutis exceeded during navigation. - the remote server does not respond or is unreachable.
- the main resource failed to load.
The method will not throw an error when any valid HTTP status code is returned by the remote server, including 404 "Not Found" and 500 "Internal Server Error". The status code for such responses can be retrieved by calling
Response.status().NOTE: The method either throws an error or returns a main resource response. The only exceptions are navigation to
about:blankor navigation to the same URL with a different hash, which would succeed and returnnull.NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.
- Parameters:
url- URL to navigate page to. The url should include scheme, e.g.https://. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.- Since:
- v1.8
-
hover
default void hover(String selector)
This method hovers over an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to hover over the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
hover
void hover(String selector, Page.HoverOptions options)
This method hovers over an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to hover over the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
innerHTML
default String innerHTML(String selector)
Returnselement.innerHTML.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
innerHTML
String innerHTML(String selector, Page.InnerHTMLOptions options)
Returnselement.innerHTML.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
innerText
default String innerText(String selector)
Returnselement.innerText.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
innerText
String innerText(String selector, Page.InnerTextOptions options)
Returnselement.innerText.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
inputValue
default String inputValue(String selector)
Returnsinput.valuefor the selected<input>or<textarea>or<select>element.Throws for non-input elements. However, if the element is inside the
<label>element that has an associated control, returns the value of the control.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
inputValue
String inputValue(String selector, Page.InputValueOptions options)
Returnsinput.valuefor the selected<input>or<textarea>or<select>element.Throws for non-input elements. However, if the element is inside the
<label>element that has an associated control, returns the value of the control.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.13
-
isChecked
default boolean isChecked(String selector)
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isChecked
boolean isChecked(String selector, Page.IsCheckedOptions options)
Returns whether the element is checked. Throws if the element is not a checkbox or radio input.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isClosed
boolean isClosed()
Indicates that the page has been closed.- Since:
- v1.8
-
isDisabled
default boolean isDisabled(String selector)
Returns whether the element is disabled, the opposite of enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isDisabled
boolean isDisabled(String selector, Page.IsDisabledOptions options)
Returns whether the element is disabled, the opposite of enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEditable
default boolean isEditable(String selector)
Returns whether the element is editable.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEditable
boolean isEditable(String selector, Page.IsEditableOptions options)
Returns whether the element is editable.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEnabled
default boolean isEnabled(String selector)
Returns whether the element is enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isEnabled
boolean isEnabled(String selector, Page.IsEnabledOptions options)
Returns whether the element is enabled.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isHidden
default boolean isHidden(String selector)
Returns whether the element is hidden, the opposite of visible.selectorthat does not match any elements is considered hidden.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isHidden
boolean isHidden(String selector, Page.IsHiddenOptions options)
Returns whether the element is hidden, the opposite of visible.selectorthat does not match any elements is considered hidden.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isVisible
default boolean isVisible(String selector)
Returns whether the element is visible.selectorthat does not match any elements is considered not visible.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
isVisible
boolean isVisible(String selector, Page.IsVisibleOptions options)
Returns whether the element is visible.selectorthat does not match any elements is considered not visible.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
keyboard
Keyboard keyboard()
- Since:
- v1.8
-
locator
default Locator locator(String selector)
The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.- Parameters:
selector- A selector to use when resolving DOM element.- Since:
- v1.14
-
locator
Locator locator(String selector, Page.LocatorOptions options)
The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.- Parameters:
selector- A selector to use when resolving DOM element.- Since:
- v1.14
-
mainFrame
Frame mainFrame()
The page's main frame. Page is guaranteed to have a main frame which persists during navigations.- Since:
- v1.8
-
mouse
Mouse mouse()
- Since:
- v1.8
-
onceDialog
void onceDialog(Consumer<Dialog> handler)
Adds one-offDialoghandler. The handler will be removed immediately after nextDialogis created.page.onceDialog(dialog -> { dialog.accept("foo"); }); // prints 'foo' System.out.println(page.evaluate("prompt('Enter string:')")); // prints 'null' as the dialog will be auto-dismissed because there are no handlers. System.out.println(page.evaluate("prompt('Enter string:')"));This code above is equivalent to:
{@code Consumer- Parameters:
handler- Receives theDialogobject, it **must** eitherDialog.accept()orDialog.dismiss()the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.- Since:
- v1.10
-
opener
Page opener()
Returns the opener for popup pages andnullfor others. If the opener has been closed already the returnsnull.- Since:
- v1.8
-
pause
void pause()
Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to callplaywright.resume()in the DevTools console.User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.
NOTE: This method requires Playwright to be started in a headed mode, with a falsy
headlessvalue in theBrowserType.launch().- Since:
- v1.9
-
pdf
default byte[] pdf()
Returns the PDF buffer.NOTE: Generating a pdf is currently only supported in Chromium headless.
page.pdf()generates a pdf of the page withprintcss media. To generate a pdf withscreenmedia, callPage.emulateMedia()before callingpage.pdf():NOTE: By default,
page.pdf()generates a pdf with modified colors for printing. Use the-webkit-print-color-adjustproperty to force rendering of exact colors.Usage
// Generates a PDF with "screen" media type. page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN)); page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));The
width,height, andmarginoptions accept values labeled with units. Unlabeled values are treated as pixels.A few examples:
-
page.pdf({width: 100})- prints with width set to 100 pixels -
page.pdf({width: '100px'})- prints with width set to 100 pixels -
page.pdf({width: '10cm'})- prints with width set to 10 centimeters.
All possible units are:
-
px- pixel -
in- inch -
cm- centimeter -
mm- millimeter
The
formatoptions are:-
Letter: 8.5in x 11in -
Legal: 8.5in x 14in -
Tabloid: 11in x 17in -
Ledger: 17in x 11in -
A0: 33.1in x 46.8in -
A1: 23.4in x 33.1in -
A2: 16.54in x 23.4in -
A3: 11.7in x 16.54in -
A4: 8.27in x 11.7in -
A5: 5.83in x 8.27in -
A6: 4.13in x 5.83in
NOTE:
headerTemplateandfooterTemplatemarkup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.- Since:
- v1.8
-
-
pdf
byte[] pdf(Page.PdfOptions options)
Returns the PDF buffer.NOTE: Generating a pdf is currently only supported in Chromium headless.
page.pdf()generates a pdf of the page withprintcss media. To generate a pdf withscreenmedia, callPage.emulateMedia()before callingpage.pdf():NOTE: By default,
page.pdf()generates a pdf with modified colors for printing. Use the-webkit-print-color-adjustproperty to force rendering of exact colors.Usage
// Generates a PDF with "screen" media type. page.emulateMedia(new Page.EmulateMediaOptions().setMedia(Media.SCREEN)); page.pdf(new Page.PdfOptions().setPath(Paths.get("page.pdf")));The
width,height, andmarginoptions accept values labeled with units. Unlabeled values are treated as pixels.A few examples:
-
page.pdf({width: 100})- prints with width set to 100 pixels -
page.pdf({width: '100px'})- prints with width set to 100 pixels -
page.pdf({width: '10cm'})- prints with width set to 10 centimeters.
All possible units are:
-
px- pixel -
in- inch -
cm- centimeter -
mm- millimeter
The
formatoptions are:-
Letter: 8.5in x 11in -
Legal: 8.5in x 14in -
Tabloid: 11in x 17in -
Ledger: 17in x 11in -
A0: 33.1in x 46.8in -
A1: 23.4in x 33.1in -
A2: 16.54in x 23.4in -
A3: 11.7in x 16.54in -
A4: 8.27in x 11.7in -
A5: 5.83in x 8.27in -
A6: 4.13in x 5.83in
NOTE:
headerTemplateandfooterTemplatemarkup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.- Since:
- v1.8
-
-
press
default void press(String selector, String key)
Focuses the element, and then usesKeyboard.down()andKeyboard.up().keycan specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of thekeyvalues can be found here. Examples of the keys are:F1-F12,Digit0-Digit9,KeyA-KeyZ,Backquote,Minus,Equal,Backslash,Backspace,Tab,Delete,Escape,ArrowDown,End,Enter,Home,Insert,PageDown,PageUp,ArrowRight,ArrowUp, etc.Following modification shortcuts are also supported:
Shift,Control,Alt,Meta,ShiftLeft,ControlOrMeta.ControlOrMetaresolves toControlon Windows and Linux and toMetaon macOS.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",key: "Control++orkey: "Control+Shift+T"are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.Usage
Page page = browser.newPage(); page.navigate("https://keycode.info"); page.press("body", "A"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png"))); page.press("body", "ArrowLeft"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" ))); page.press("body", "Shift+O"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" )));- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.key- Name of the key to press or a character to generate, such asArrowLeftora.- Since:
- v1.8
-
press
void press(String selector, String key, Page.PressOptions options)
Focuses the element, and then usesKeyboard.down()andKeyboard.up().keycan specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of thekeyvalues can be found here. Examples of the keys are:F1-F12,Digit0-Digit9,KeyA-KeyZ,Backquote,Minus,Equal,Backslash,Backspace,Tab,Delete,Escape,ArrowDown,End,Enter,Home,Insert,PageDown,PageUp,ArrowRight,ArrowUp, etc.Following modification shortcuts are also supported:
Shift,Control,Alt,Meta,ShiftLeft,ControlOrMeta.ControlOrMetaresolves toControlon Windows and Linux and toMetaon macOS.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",key: "Control++orkey: "Control+Shift+T"are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.Usage
Page page = browser.newPage(); page.navigate("https://keycode.info"); page.press("body", "A"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("A.png"))); page.press("body", "ArrowLeft"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("ArrowLeft.png" ))); page.press("body", "Shift+O"); page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("O.png" )));- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.key- Name of the key to press or a character to generate, such asArrowLeftora.- Since:
- v1.8
-
querySelector
default ElementHandle querySelector(String selector)
The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves tonull. To wait for an element on the page, useLocator.waitFor().- Parameters:
selector- A selector to query for.- Since:
- v1.9
-
querySelector
ElementHandle querySelector(String selector, Page.QuerySelectorOptions options)
The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves tonull. To wait for an element on the page, useLocator.waitFor().- Parameters:
selector- A selector to query for.- Since:
- v1.9
-
querySelectorAll
List<ElementHandle> querySelectorAll(String selector)
The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to[].- Parameters:
selector- A selector to query for.- Since:
- v1.9
-
addLocatorHandler
default void addLocatorHandler(Locator locator, Consumer<Locator> handler)
When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
Things to keep in mind:
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of
your normal test flow, instead of using
Page.addLocatorHandler(). - Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
- After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You
can opt-out of this behavior with
noWaitAfter. - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
- You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
NOTE: Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.
For example, consider a test that callsLocator.focus()followed byKeyboard.press(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. UseLocator.press()instead to avoid this problem.
Another example is a series of mouse actions, whereMouse.move()is followed byMouse.down(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions likeLocator.click()that do not rely on the state being unchanged by a handler.Usage
An example that closes a "Sign up to the newsletter" dialog when it appears:
// Setup the handler. page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => { page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click(); }); // Write the test as usual. page.goto("https://example.com"); page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();An example that skips the "Confirm your security details" page when it is shown:
// Setup the handler. page.addLocatorHandler(page.getByText("Confirm your security details")), () => { page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click(); }); // Write the test as usual. page.goto("https://example.com"); page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();An example with a custom callback on every actionability check. It uses a
<body>locator that is always visible, so the handler is called before every actionability check. It is important to specifynoWaitAfter, because the handler does not hide the<body>element.// Setup the handler. page.addLocatorHandler(page.locator("body")), () => { page.evaluate("window.removeObstructionsForTestIfNeeded()"); }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true)); // Write the test as usual. page.goto("https://example.com"); page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting
times:page.addLocatorHandler(page.getByLabel("Close"), locator => { locator.click(); }, new Page.AddLocatorHandlerOptions().setTimes(1));- Parameters:
locator- Locator that triggers the handler.handler- Function that should be run oncelocatorappears. This function should get rid of the element that blocks actions like click.- Since:
- v1.42
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of
your normal test flow, instead of using
-
addLocatorHandler
void addLocatorHandler(Locator locator, Consumer<Locator> handler, Page.AddLocatorHandlerOptions options)
When testing a web page, sometimes unexpected overlays like a "Sign up" dialog appear and block actions you want to automate, e.g. clicking a button. These overlays don't always show up in the same way or at the same time, making them tricky to handle in automated tests.This method lets you set up a special function, called a handler, that activates when it detects that overlay is visible. The handler's job is to remove the overlay, allowing your test to continue as if the overlay wasn't there.
Things to keep in mind:
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of
your normal test flow, instead of using
Page.addLocatorHandler(). - Playwright checks for the overlay every time before executing or retrying an action that requires an actionability check, or before performing an auto-waiting assertion check. When overlay is visible, Playwright calls the handler first, and then proceeds with the action/assertion. Note that the handler is only called when you perform an action/assertion - if the overlay becomes visible but you don't perform any actions, the handler will not be triggered.
- After executing the handler, Playwright will ensure that overlay that triggered the handler is not visible anymore. You
can opt-out of this behavior with
noWaitAfter. - The execution time of the handler counts towards the timeout of the action/assertion that executed the handler. If your handler takes too long, it might cause timeouts.
- You can register multiple handlers. However, only a single handler will be running at a time. Make sure the actions within a handler don't depend on another handler.
NOTE: Running the handler will alter your page state mid-test. For example it will change the currently focused element and move the mouse. Make sure that actions that run after the handler are self-contained and do not rely on the focus and mouse state being unchanged.
For example, consider a test that callsLocator.focus()followed byKeyboard.press(). If your handler clicks a button between these two actions, the focused element most likely will be wrong, and key press will happen on the unexpected element. UseLocator.press()instead to avoid this problem.
Another example is a series of mouse actions, whereMouse.move()is followed byMouse.down(). Again, when the handler runs between these two actions, the mouse position will be wrong during the mouse down. Prefer self-contained actions likeLocator.click()that do not rely on the state being unchanged by a handler.Usage
An example that closes a "Sign up to the newsletter" dialog when it appears:
// Setup the handler. page.addLocatorHandler(page.getByText("Sign up to the newsletter"), () => { page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("No thanks")).click(); }); // Write the test as usual. page.goto("https://example.com"); page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();An example that skips the "Confirm your security details" page when it is shown:
// Setup the handler. page.addLocatorHandler(page.getByText("Confirm your security details")), () => { page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Remind me later")).click(); }); // Write the test as usual. page.goto("https://example.com"); page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();An example with a custom callback on every actionability check. It uses a
<body>locator that is always visible, so the handler is called before every actionability check. It is important to specifynoWaitAfter, because the handler does not hide the<body>element.// Setup the handler. page.addLocatorHandler(page.locator("body")), () => { page.evaluate("window.removeObstructionsForTestIfNeeded()"); }, new Page.AddLocatorHandlerOptions.setNoWaitAfter(true)); // Write the test as usual. page.goto("https://example.com"); page.getByRole("button", Page.GetByRoleOptions().setName("Start here")).click();Handler takes the original locator as an argument. You can also automatically remove the handler after a number of invocations by setting
times:page.addLocatorHandler(page.getByLabel("Close"), locator => { locator.click(); }, new Page.AddLocatorHandlerOptions().setTimes(1));- Parameters:
locator- Locator that triggers the handler.handler- Function that should be run oncelocatorappears. This function should get rid of the element that blocks actions like click.- Since:
- v1.42
- When an overlay is shown predictably, we recommend explicitly waiting for it in your test and dismissing it as a part of
your normal test flow, instead of using
-
removeLocatorHandler
void removeLocatorHandler(Locator locator)
Removes all locator handlers added byPage.addLocatorHandler()for a specific locator.- Parameters:
locator- Locator passed toPage.addLocatorHandler().- Since:
- v1.44
-
reload
default Response reload()
This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.- Since:
- v1.8
-
reload
Response reload(Page.ReloadOptions options)
This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.- Since:
- v1.8
-
request
APIRequestContext request()
API testing helper associated with this page. This method returns the same instance asBrowserContext.request()on the page's context. SeeBrowserContext.request()for more details.- Since:
- v1.16
-
route
default void route(String url, Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by a page.Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".NOTE:
Page.route()will not intercept the first request of a popup page. UseBrowserContext.route()instead.Usage
An example of a naive handler that aborts all image requests:
Page page = browser.newPage(); page.route("**\/*.{png,jpg,jpeg}", route -> route.abort()); page.navigate("https://example.com"); browser.close();or the same snippet using a regex pattern instead:
Page page = browser.newPage(); page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); page.navigate("https://example.com"); browser.close();It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); });Page routes take precedence over browser context routes (set up with
BrowserContext.route()) when request matches both handlers.To remove a route with its handler you can use
Page.unroute().NOTE: Enabling routing disables http cache.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
void route(String url, Consumer<Route> handler, Page.RouteOptions options)
Routing provides the capability to modify network requests that are made by a page.Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".NOTE:
Page.route()will not intercept the first request of a popup page. UseBrowserContext.route()instead.Usage
An example of a naive handler that aborts all image requests:
Page page = browser.newPage(); page.route("**\/*.{png,jpg,jpeg}", route -> route.abort()); page.navigate("https://example.com"); browser.close();or the same snippet using a regex pattern instead:
Page page = browser.newPage(); page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); page.navigate("https://example.com"); browser.close();It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); });Page routes take precedence over browser context routes (set up with
BrowserContext.route()) when request matches both handlers.To remove a route with its handler you can use
Page.unroute().NOTE: Enabling routing disables http cache.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
default void route(Pattern url, Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by a page.Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".NOTE:
Page.route()will not intercept the first request of a popup page. UseBrowserContext.route()instead.Usage
An example of a naive handler that aborts all image requests:
Page page = browser.newPage(); page.route("**\/*.{png,jpg,jpeg}", route -> route.abort()); page.navigate("https://example.com"); browser.close();or the same snippet using a regex pattern instead:
Page page = browser.newPage(); page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); page.navigate("https://example.com"); browser.close();It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); });Page routes take precedence over browser context routes (set up with
BrowserContext.route()) when request matches both handlers.To remove a route with its handler you can use
Page.unroute().NOTE: Enabling routing disables http cache.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
void route(Pattern url, Consumer<Route> handler, Page.RouteOptions options)
Routing provides the capability to modify network requests that are made by a page.Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".NOTE:
Page.route()will not intercept the first request of a popup page. UseBrowserContext.route()instead.Usage
An example of a naive handler that aborts all image requests:
Page page = browser.newPage(); page.route("**\/*.{png,jpg,jpeg}", route -> route.abort()); page.navigate("https://example.com"); browser.close();or the same snippet using a regex pattern instead:
Page page = browser.newPage(); page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); page.navigate("https://example.com"); browser.close();It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); });Page routes take precedence over browser context routes (set up with
BrowserContext.route()) when request matches both handlers.To remove a route with its handler you can use
Page.unroute().NOTE: Enabling routing disables http cache.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
default void route(Predicate<String> url, Consumer<Route> handler)
Routing provides the capability to modify network requests that are made by a page.Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".NOTE:
Page.route()will not intercept the first request of a popup page. UseBrowserContext.route()instead.Usage
An example of a naive handler that aborts all image requests:
Page page = browser.newPage(); page.route("**\/*.{png,jpg,jpeg}", route -> route.abort()); page.navigate("https://example.com"); browser.close();or the same snippet using a regex pattern instead:
Page page = browser.newPage(); page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); page.navigate("https://example.com"); browser.close();It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); });Page routes take precedence over browser context routes (set up with
BrowserContext.route()) when request matches both handlers.To remove a route with its handler you can use
Page.unroute().NOTE: Enabling routing disables http cache.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
route
void route(Predicate<String> url, Consumer<Route> handler, Page.RouteOptions options)
Routing provides the capability to modify network requests that are made by a page.Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.
NOTE: The handler will only be called for the first url if the response is a redirect.
NOTE:
Page.route()will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by settingBrowser.newContext.serviceWorkersto"block".NOTE:
Page.route()will not intercept the first request of a popup page. UseBrowserContext.route()instead.Usage
An example of a naive handler that aborts all image requests:
Page page = browser.newPage(); page.route("**\/*.{png,jpg,jpeg}", route -> route.abort()); page.navigate("https://example.com"); browser.close();or the same snippet using a regex pattern instead:
Page page = browser.newPage(); page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort()); page.navigate("https://example.com"); browser.close();It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:
page.route("/api/**", route -> { if (route.request().postData().contains("my-string")) route.fulfill(new Route.FulfillOptions().setBody("mocked-data")); else route.resume(); });Page routes take precedence over browser context routes (set up with
BrowserContext.route()) when request matches both handlers.To remove a route with its handler you can use
Page.unroute().NOTE: Enabling routing disables http cache.
- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.handler- handler function to route the request.- Since:
- v1.8
-
routeFromHAR
default void routeFromHAR(Path har)
If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting
Browser.newContext.serviceWorkersto"block".- Parameters:
har- Path to a HAR file with prerecorded network data. Ifpathis a relative path, then it is resolved relative to the current working directory.- Since:
- v1.23
-
routeFromHAR
void routeFromHAR(Path har, Page.RouteFromHAROptions options)
If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting
Browser.newContext.serviceWorkersto"block".- Parameters:
har- Path to a HAR file with prerecorded network data. Ifpathis a relative path, then it is resolved relative to the current working directory.- Since:
- v1.23
-
screenshot
default byte[] screenshot()
Returns the buffer with the captured screenshot.- Since:
- v1.8
-
screenshot
byte[] screenshot(Page.ScreenshotOptions options)
Returns the buffer with the captured screenshot.- Since:
- v1.8
-
selectOption
default List<String> selectOption(String selector, String values)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, 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.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
default List<String> selectOption(String selector, ElementHandle values)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, ElementHandle values, Page.SelectOptionOptions options)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
default List<String> selectOption(String selector, String[] values)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, 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.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
default List<String> selectOption(String selector, SelectOption values)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, 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.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
default List<String> selectOption(String selector, ElementHandle[] values)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, ElementHandle[] values, Page.SelectOptionOptions options)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
default List<String> selectOption(String selector, SelectOption[] values)
This method waits for an element matchingselector, waits for actionability checks, waits until all specified options are present in the<select>element and selects these options.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
selectOption
List<String> selectOption(String selector, 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.If the target element is not a
<select>element, this method throws an error. However, if the element is inside the<label>element that has an associated control, the control will be used instead.Returns the array of option values that have been successfully selected.
Triggers a
changeandinputevent once all the provided options have been selected.Usage
// Single selection matching the value or label page.selectOption("select#colors", "blue"); // single selection matching both the value and the label page.selectOption("select#colors", new SelectOption().setLabel("Blue")); // multiple selection page.selectOption("select#colors", new String[] {"red", "green", "blue"});- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.values- Options to select. If the<select>has themultipleattribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.- Since:
- v1.8
-
setChecked
default void setChecked(String selector, boolean checked)
This method checks or unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- If the element already has the right checked state, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked or unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.checked- Whether to check or uncheck the checkbox.- Since:
- v1.15
- Find an element matching
-
setChecked
void setChecked(String selector, boolean checked, Page.SetCheckedOptions options)
This method checks or unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws.
- If the element already has the right checked state, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now checked or unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.checked- Whether to check or uncheck the checkbox.- Since:
- v1.15
- Find an element matching
-
setContent
default void setContent(String html)
This method internally calls document.write(), inheriting all its specific characteristics and behaviors.- Parameters:
html- HTML markup to assign to the page.- Since:
- v1.8
-
setContent
void setContent(String html, Page.SetContentOptions options)
This method internally calls document.write(), inheriting all its specific characteristics and behaviors.- Parameters:
html- HTML markup to assign to the page.- Since:
- v1.8
-
setDefaultNavigationTimeout
void setDefaultNavigationTimeout(double timeout)
This setting will change the default maximum navigation time for the following methods and related shortcuts:-
Page.goBack() -
Page.goForward() -
Page.navigate() -
Page.reload() -
Page.setContent() -
Page.waitForNavigation() -
Page.waitForURL()
NOTE:
Page.setDefaultNavigationTimeout()takes priority overPage.setDefaultTimeout(),BrowserContext.setDefaultTimeout()andBrowserContext.setDefaultNavigationTimeout().- Parameters:
timeout- Maximum navigation time in milliseconds- Since:
- v1.8
-
-
setDefaultTimeout
void setDefaultTimeout(double timeout)
This setting will change the default maximum time for all the methods acceptingtimeoutoption.NOTE:
Page.setDefaultNavigationTimeout()takes priority overPage.setDefaultTimeout().- Parameters:
timeout- Maximum time in milliseconds- Since:
- v1.8
-
setExtraHTTPHeaders
void setExtraHTTPHeaders(Map<String,String> headers)
The extra HTTP headers will be sent with every request the page initiates.NOTE:
Page.setExtraHTTPHeaders()does not guarantee the order of headers in the outgoing requests.- Parameters:
headers- An object containing additional HTTP headers to be sent with every request. All header values must be strings.- Since:
- v1.8
-
setInputFiles
default void setInputFiles(String selector, Path files)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
void setInputFiles(String selector, Path files, Page.SetInputFilesOptions options)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
default void setInputFiles(String selector, Path[] files)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
void setInputFiles(String selector, Path[] files, Page.SetInputFilesOptions options)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
default void setInputFiles(String selector, FilePayload files)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
void setInputFiles(String selector, FilePayload files, Page.SetInputFilesOptions options)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
default void setInputFiles(String selector, FilePayload[] files)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setInputFiles
void setInputFiles(String selector, FilePayload[] files, Page.SetInputFilesOptions options)
Sets the value of the file input to these file paths or files. If some of thefilePathsare relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files. For inputs with a[webkitdirectory]attribute, only a single directory path is supported.This method expects
selectorto point to an input element. However, if the element is inside the<label>element that has an associated control, targets the control instead.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
setViewportSize
void setViewportSize(int width, int height)In the case of multiple pages in a single browser, each page can have its own viewport size. However,Browser.newContext()allows to set viewport size (and more) for all pages in the context at once.Page.setViewportSize()will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page.Page.setViewportSize()will also resetscreensize, useBrowser.newContext()withscreenandviewportparameters if you need better control of these properties.Usage
Page page = browser.newPage(); page.setViewportSize(640, 480); page.navigate("https://example.com");- Since:
- v1.8
-
tap
default void tap(String selector)
This method taps an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.touchscreen()to tap the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
Page.tap()the method will throw ifhasTouchoption of the browser context is false.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
tap
void tap(String selector, Page.TapOptions options)
This method taps an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.touchscreen()to tap the center of the element, or the specifiedposition. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.NOTE:
Page.tap()the method will throw ifhasTouchoption of the browser context is false.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
textContent
default String textContent(String selector)
Returnselement.textContent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
textContent
String textContent(String selector, Page.TextContentOptions options)
Returnselement.textContent.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
-
title
String title()
Returns the page's title.- Since:
- v1.8
-
touchscreen
Touchscreen touchscreen()
- Since:
- v1.8
-
type
default void type(String selector, String text)
Deprecated.In most cases, you should useLocator.fill()instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case useLocator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.text- A text to type into a focused element.- Since:
- v1.8
-
type
void type(String selector, String text, Page.TypeOptions options)
Deprecated.In most cases, you should useLocator.fill()instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case useLocator.pressSequentially().- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.text- A text to type into a focused element.- Since:
- v1.8
-
uncheck
default void uncheck(String selector)
This method unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
uncheck
void uncheck(String selector, Page.UncheckOptions options)
This method unchecks an element matchingselectorby performing the following steps:- Find an element matching
selector. If there is none, wait until a matching element is attached to the DOM. - Ensure that matched element is a checkbox or a radio input. If not, this method throws. If the element is already unchecked, this method returns immediately.
- Wait for actionability checks on the matched element,
unless
forceoption is set. If the element is detached during the checks, the whole action is retried. - Scroll the element into view if needed.
- Use
Page.mouse()to click in the center of the element. - Wait for initiated navigations to either succeed or fail, unless
noWaitAfteroption is set. - Ensure that the element is now unchecked. If not, this method throws.
When all steps combined have not finished during the specified
timeout, this method throws aTimeoutError. Passing zero timeout disables this.- Parameters:
selector- A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.- Since:
- v1.8
- Find an element matching
-
unrouteAll
void unrouteAll()
Removes all routes created withPage.route()andPage.routeFromHAR().- Since:
- v1.41
-
unroute
default void unroute(String url)
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.- Since:
- v1.8
-
unroute
void unroute(String url, Consumer<Route> handler)
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler- Optional handler function to route the request.- Since:
- v1.8
-
unroute
default void unroute(Pattern url)
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.- Since:
- v1.8
-
unroute
void unroute(Pattern url, Consumer<Route> handler)
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler- Optional handler function to route the request.- Since:
- v1.8
-
unroute
default void unroute(Predicate<String> url)
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.- Since:
- v1.8
-
unroute
void unroute(Predicate<String> url, Consumer<Route> handler)
Removes a route created withPage.route(). Whenhandleris not specified, removes all routes for theurl.- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while routing.handler- Optional handler function to route the request.- Since:
- v1.8
-
url
String url()
- Since:
- v1.8
-
video
Video video()
Video object associated with this page.- Since:
- v1.8
-
viewportSize
ViewportSize viewportSize()
- Since:
- v1.8
-
waitForClose
default Page waitForClose(Runnable callback)
Performs action and waits for the Page to close.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.11
-
waitForClose
Page waitForClose(Page.WaitForCloseOptions options, Runnable callback)
Performs action and waits for the Page to close.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.11
-
waitForConsoleMessage
default ConsoleMessage waitForConsoleMessage(Runnable callback)
Performs action and waits for aConsoleMessageto be logged by in the page. If predicate is provided, it passesConsoleMessagevalue into thepredicatefunction and waits forpredicate(message)to return a truthy value. Will throw an error if the page is closed before thePage.onConsoleMessage()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForConsoleMessage
ConsoleMessage waitForConsoleMessage(Page.WaitForConsoleMessageOptions options, Runnable callback)
Performs action and waits for aConsoleMessageto be logged by in the page. If predicate is provided, it passesConsoleMessagevalue into thepredicatefunction and waits forpredicate(message)to return a truthy value. Will throw an error if the page is closed before thePage.onConsoleMessage()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForDownload
default Download waitForDownload(Runnable callback)
Performs action and waits for a newDownload. If predicate is provided, it passesDownloadvalue into thepredicatefunction and waits forpredicate(download)to return a truthy value. Will throw an error if the page is closed before the download event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForDownload
Download waitForDownload(Page.WaitForDownloadOptions options, Runnable callback)
Performs action and waits for a newDownload. If predicate is provided, it passesDownloadvalue into thepredicatefunction and waits forpredicate(download)to return a truthy value. Will throw an error if the page is closed before the download event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForFileChooser
default FileChooser waitForFileChooser(Runnable callback)
Performs action and waits for a newFileChooserto be created. If predicate is provided, it passesFileChooservalue into thepredicatefunction and waits forpredicate(fileChooser)to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForFileChooser
FileChooser waitForFileChooser(Page.WaitForFileChooserOptions options, Runnable callback)
Performs action and waits for a newFileChooserto be created. If predicate is provided, it passesFileChooservalue into thepredicatefunction and waits forpredicate(fileChooser)to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForFunction
default JSHandle waitForFunction(String expression, Object arg)
Returns when theexpressionreturns a truthy value. It resolves to a JSHandle of the truthy value.Usage
The
Page.waitForFunction()can be used to observe viewport size change:import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch(); Page page = browser.newPage(); page.setViewportSize(50, 50); page.waitForFunction("() => window.innerWidth < 100"); browser.close(); } } }To pass an argument to the predicate of
Page.waitForFunction()function:String selector = ".foo"; page.waitForFunction("selector => !!document.querySelector(selector)", selector);- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
waitForFunction
default JSHandle waitForFunction(String expression)
Returns when theexpressionreturns a truthy value. It resolves to a JSHandle of the truthy value.Usage
The
Page.waitForFunction()can be used to observe viewport size change:import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch(); Page page = browser.newPage(); page.setViewportSize(50, 50); page.waitForFunction("() => window.innerWidth < 100"); browser.close(); } } }To pass an argument to the predicate of
Page.waitForFunction()function:String selector = ".foo"; page.waitForFunction("selector => !!document.querySelector(selector)", selector);- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.- Since:
- v1.8
-
waitForFunction
JSHandle waitForFunction(String expression, Object arg, Page.WaitForFunctionOptions options)
Returns when theexpressionreturns a truthy value. It resolves to a JSHandle of the truthy value.Usage
The
Page.waitForFunction()can be used to observe viewport size change:import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType webkit = playwright.webkit(); Browser browser = webkit.launch(); Page page = browser.newPage(); page.setViewportSize(50, 50); page.waitForFunction("() => window.innerWidth < 100"); browser.close(); } } }To pass an argument to the predicate of
Page.waitForFunction()function:String selector = ".foo"; page.waitForFunction("selector => !!document.querySelector(selector)", selector);- Parameters:
expression- JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.arg- Optional argument to pass toexpression.- Since:
- v1.8
-
waitForLoadState
default void waitForLoadState(LoadState state)
Returns when the required load state has been reached.This resolves when the page reaches a required load state,
loadby default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action.
Usage
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation. page.waitForLoadState(); // The promise resolves after "load" event.Page popup = page.waitForPopup(() -> { page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup. }); // Wait for the "DOMContentLoaded" event popup.waitForLoadState(LoadState.DOMCONTENTLOADED); System.out.println(popup.title()); // Popup is ready to use.- Parameters:
state- Optional load state to wait for, defaults toload. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:-
"load"- wait for theloadevent to be fired. -
"domcontentloaded"- wait for theDOMContentLoadedevent to be fired. -
"networkidle"- **DISCOURAGED** wait until there are no network connections for at least500ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
-
- Since:
- v1.8
-
waitForLoadState
default void waitForLoadState()
Returns when the required load state has been reached.This resolves when the page reaches a required load state,
loadby default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action.
Usage
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation. page.waitForLoadState(); // The promise resolves after "load" event.Page popup = page.waitForPopup(() -> { page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup. }); // Wait for the "DOMContentLoaded" event popup.waitForLoadState(LoadState.DOMCONTENTLOADED); System.out.println(popup.title()); // Popup is ready to use.- Since:
- v1.8
-
waitForLoadState
void waitForLoadState(LoadState state, Page.WaitForLoadStateOptions options)
Returns when the required load state has been reached.This resolves when the page reaches a required load state,
loadby default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.NOTE: Most of the time, this method is not needed because Playwright auto-waits before every action.
Usage
page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation. page.waitForLoadState(); // The promise resolves after "load" event.Page popup = page.waitForPopup(() -> { page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup. }); // Wait for the "DOMContentLoaded" event popup.waitForLoadState(LoadState.DOMCONTENTLOADED); System.out.println(popup.title()); // Popup is ready to use.- Parameters:
state- Optional load state to wait for, defaults toload. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:-
"load"- wait for theloadevent to be fired. -
"domcontentloaded"- wait for theDOMContentLoadedevent to be fired. -
"networkidle"- **DISCOURAGED** wait until there are no network connections for at least500ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
-
- Since:
- v1.8
-
waitForNavigation
default Response waitForNavigation(Runnable callback)
Deprecated.This method is inherently racy, please usePage.waitForURL()instead.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForNavigation
Response waitForNavigation(Page.WaitForNavigationOptions options, Runnable callback)
Deprecated.This method is inherently racy, please usePage.waitForURL()instead.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForPopup
default Page waitForPopup(Runnable callback)
Performs action and waits for a popupPage. If predicate is provided, it passes [Popup] value into thepredicatefunction and waits forpredicate(page)to return a truthy value. Will throw an error if the page is closed before the popup event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForPopup
Page waitForPopup(Page.WaitForPopupOptions options, Runnable callback)
Performs action and waits for a popupPage. If predicate is provided, it passes [Popup] value into thepredicatefunction and waits forpredicate(page)to return a truthy value. Will throw an error if the page is closed before the popup event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForRequest
default Request waitForRequest(String urlOrPredicate, Runnable callback)
Waits for the matching request and returns it. See waiting for event for more details about events.Usage
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // Waits for the next request matching some conditions Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { // Triggers the request page.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Request waitForRequest(String urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)
Waits for the matching request and returns it. See waiting for event for more details about events.Usage
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // Waits for the next request matching some conditions Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { // Triggers the request page.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
default Request waitForRequest(Pattern urlOrPredicate, Runnable callback)
Waits for the matching request and returns it. See waiting for event for more details about events.Usage
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // Waits for the next request matching some conditions Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { // Triggers the request page.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Request waitForRequest(Pattern urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)
Waits for the matching request and returns it. See waiting for event for more details about events.Usage
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // Waits for the next request matching some conditions Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { // Triggers the request page.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
default Request waitForRequest(Predicate<Request> urlOrPredicate, Runnable callback)
Waits for the matching request and returns it. See waiting for event for more details about events.Usage
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // Waits for the next request matching some conditions Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { // Triggers the request page.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequest
Request waitForRequest(Predicate<Request> urlOrPredicate, Page.WaitForRequestOptions options, Runnable callback)
Waits for the matching request and returns it. See waiting for event for more details about events.Usage
// Waits for the next request with the specified url Request request = page.waitForRequest("https://example.com/resource", () -> { // Triggers the request page.getByText("trigger request").click(); }); // Waits for the next request matching some conditions Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> { // Triggers the request page.getByText("trigger request").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingRequestobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForRequestFinished
default Request waitForRequestFinished(Runnable callback)
Performs action and waits for aRequestto finish loading. If predicate is provided, it passesRequestvalue into thepredicatefunction and waits forpredicate(request)to return a truthy value. Will throw an error if the page is closed before thePage.onRequestFinished()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.12
-
waitForRequestFinished
Request waitForRequestFinished(Page.WaitForRequestFinishedOptions options, Runnable callback)
Performs action and waits for aRequestto finish loading. If predicate is provided, it passesRequestvalue into thepredicatefunction and waits forpredicate(request)to return a truthy value. Will throw an error if the page is closed before thePage.onRequestFinished()event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.12
-
waitForResponse
default Response waitForResponse(String urlOrPredicate, Runnable callback)
Returns the matched response. See waiting for event for more details about events.Usage
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // Waits for the next response matching some conditions Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> { // Triggers the response page.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Response waitForResponse(String urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)
Returns the matched response. See waiting for event for more details about events.Usage
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // Waits for the next response matching some conditions Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> { // Triggers the response page.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
default Response waitForResponse(Pattern urlOrPredicate, Runnable callback)
Returns the matched response. See waiting for event for more details about events.Usage
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // Waits for the next response matching some conditions Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> { // Triggers the response page.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Response waitForResponse(Pattern urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)
Returns the matched response. See waiting for event for more details about events.Usage
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // Waits for the next response matching some conditions Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> { // Triggers the response page.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
default Response waitForResponse(Predicate<Response> urlOrPredicate, Runnable callback)
Returns the matched response. See waiting for event for more details about events.Usage
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // Waits for the next response matching some conditions Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> { // Triggers the response page.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForResponse
Response waitForResponse(Predicate<Response> urlOrPredicate, Page.WaitForResponseOptions options, Runnable callback)
Returns the matched response. See waiting for event for more details about events.Usage
// Waits for the next response with the specified url Response response = page.waitForResponse("https://example.com/resource", () -> { // Triggers the response page.getByText("trigger response").click(); }); // Waits for the next response matching some conditions Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200 && "GET".equals(response.request().method()), () -> { // Triggers the response page.getByText("trigger response").click(); });- Parameters:
urlOrPredicate- Request URL string, regex or predicate receivingResponseobject. When abaseURLvia the context options was provided and the passed URL is a path, it gets merged via thenew URL()constructor.callback- Callback that performs the action triggering the event.- Since:
- v1.8
-
waitForSelector
default ElementHandle waitForSelector(String selector)
Returns when element specified by selector satisfiesstateoption. Returnsnullif waiting forhiddenordetached.NOTE: Playwright automatically waits for element to be ready before performing an action. Using
Locatorobjects and web-first assertions makes the code wait-for-selector-free.Wait for the
selectorto satisfystateoption (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the methodselectoralready satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for thetimeoutmilliseconds, the function will throw.Usage
This method works across navigations:
import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType chromium = playwright.chromium(); Browser browser = chromium.launch(); Page page = browser.newPage(); for (String currentURL : Arrays.asList("https://google.com", "https://bbc.com")) { page.navigate(currentURL); ElementHandle element = page.waitForSelector("img"); System.out.println("Loaded image: " + element.getAttribute("src")); } browser.close(); } } }- Parameters:
selector- A selector to query for.- Since:
- v1.8
-
waitForSelector
ElementHandle waitForSelector(String selector, Page.WaitForSelectorOptions options)
Returns when element specified by selector satisfiesstateoption. Returnsnullif waiting forhiddenordetached.NOTE: Playwright automatically waits for element to be ready before performing an action. Using
Locatorobjects and web-first assertions makes the code wait-for-selector-free.Wait for the
selectorto satisfystateoption (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the methodselectoralready satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for thetimeoutmilliseconds, the function will throw.Usage
This method works across navigations:
import com.microsoft.playwright.*; public class Example { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { BrowserType chromium = playwright.chromium(); Browser browser = chromium.launch(); Page page = browser.newPage(); for (String currentURL : Arrays.asList("https://google.com", "https://bbc.com")) { page.navigate(currentURL); ElementHandle element = page.waitForSelector("img"); System.out.println("Loaded image: " + element.getAttribute("src")); } browser.close(); } } }- Parameters:
selector- A selector to query for.- Since:
- v1.8
-
waitForCondition
default void waitForCondition(BooleanSupplier condition)
The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.Usage
Use the method to wait for a condition that depends on page events:
List<String> messages = new ArrayList<>(); page.onConsoleMessage(m -> messages.add(m.text())); page.getByText("Submit button").click(); page.waitForCondition(() -> messages.size() > 3);- Parameters:
condition- Condition to wait for.- Since:
- v1.32
-
waitForCondition
void waitForCondition(BooleanSupplier condition, Page.WaitForConditionOptions options)
The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.Usage
Use the method to wait for a condition that depends on page events:
List<String> messages = new ArrayList<>(); page.onConsoleMessage(m -> messages.add(m.text())); page.getByText("Submit button").click(); page.waitForCondition(() -> messages.size() > 3);- Parameters:
condition- Condition to wait for.- Since:
- v1.32
-
waitForTimeout
void waitForTimeout(double timeout)
Waits for the giventimeoutin milliseconds.Note that
page.waitForTimeout()should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.Usage
// wait for 1 second page.waitForTimeout(1000);- Parameters:
timeout- A timeout to wait for- Since:
- v1.8
-
waitForURL
default void waitForURL(String url)
Waits for the main frame to navigate to the given URL.Usage
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
void waitForURL(String url, Page.WaitForURLOptions options)
Waits for the main frame to navigate to the given URL.Usage
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
default void waitForURL(Pattern url)
Waits for the main frame to navigate to the given URL.Usage
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
void waitForURL(Pattern url, Page.WaitForURLOptions options)
Waits for the main frame to navigate to the given URL.Usage
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
default void waitForURL(Predicate<String> url)
Waits for the main frame to navigate to the given URL.Usage
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForURL
void waitForURL(Predicate<String> url, Page.WaitForURLOptions options)
Waits for the main frame to navigate to the given URL.Usage
page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation page.waitForURL("**\/target.html");- Parameters:
url- A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.- Since:
- v1.11
-
waitForWebSocket
default WebSocket waitForWebSocket(Runnable callback)
Performs action and waits for a newWebSocket. If predicate is provided, it passesWebSocketvalue into thepredicatefunction and waits forpredicate(webSocket)to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForWebSocket
WebSocket waitForWebSocket(Page.WaitForWebSocketOptions options, Runnable callback)
Performs action and waits for a newWebSocket. If predicate is provided, it passesWebSocketvalue into thepredicatefunction and waits forpredicate(webSocket)to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForWorker
default Worker waitForWorker(Runnable callback)
Performs action and waits for a newWorker. If predicate is provided, it passesWorkervalue into thepredicatefunction and waits forpredicate(worker)to return a truthy value. Will throw an error if the page is closed before the worker event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
waitForWorker
Worker waitForWorker(Page.WaitForWorkerOptions options, Runnable callback)
Performs action and waits for a newWorker. If predicate is provided, it passesWorkervalue into thepredicatefunction and waits forpredicate(worker)to return a truthy value. Will throw an error if the page is closed before the worker event is fired.- Parameters:
callback- Callback that performs the action triggering the event.- Since:
- v1.9
-
workers
List<Worker> workers()
This method returns all of the dedicated WebWorkers associated with the page.NOTE: This does not contain ServiceWorkers
- Since:
- v1.8
-
-