Class PageImpl

  • All Implemented Interfaces:
    Page, java.lang.AutoCloseable

    public class PageImpl
    extends ChannelOwner
    implements Page
    • Constructor Detail

      • PageImpl

        PageImpl​(ChannelOwner parent,
                 java.lang.String type,
                 java.lang.String guid,
                 com.google.gson.JsonObject initializer)
    • Method Detail

      • eventSubscriptions

        private static final java.util.Map<PageImpl.EventType,​java.lang.String> eventSubscriptions()
      • handleEvent

        protected void handleEvent​(java.lang.String event,
                                   com.google.gson.JsonObject params)
        Overrides:
        handleEvent in class ChannelOwner
      • notifyPopup

        void notifyPopup​(PageImpl popup)
      • didClose

        void didClose()
      • onClose

        public void onClose​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Emitted when the page closes.
        Specified by:
        onClose in interface Page
      • offClose

        public void offClose​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onClose(handler).
        Specified by:
        offClose in interface Page
      • onConsoleMessage

        public void onConsoleMessage​(java.util.function.Consumer<ConsoleMessage> handler)
        Description copied from interface: Page
        Emitted when JavaScript within the page calls one of console API methods, e.g. console.log or console.dir. Also emitted if the page throws an error or a warning.

        The arguments passed into console.log are available on the ConsoleMessage event handler argument.

        **Usage**

        
         page.onConsoleMessage(msg -> {
           for (int i = 0; i < msg.args().size(); ++i)
             System.out.println(i + ": " + msg.args().get(i).jsonValue());
         });
         page.evaluate("() => console.log('hello', 5, { foo: 'bar' })");
         
        Specified by:
        onConsoleMessage in interface Page
      • onCrash

        public void onCrash​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        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".
         }
         
        Specified by:
        onCrash in interface Page
      • offCrash

        public void offCrash​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onCrash(handler).
        Specified by:
        offCrash in interface Page
      • onDialog

        public void onDialog​(java.util.function.Consumer<Dialog> handler)
        Description copied from interface: Page
        Emitted when a JavaScript dialog appears, such as alert, prompt, confirm or beforeunload. Listener **must** either Dialog.accept() or Dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.

        **Usage**

        
         page.onDialog(dialog -> {
           dialog.accept();
         });
         

        NOTE: When no Page.onDialog() or BrowserContext.onDialog() listeners are present, all dialogs are automatically dismissed.

        Specified by:
        onDialog in interface Page
      • offDialog

        public void offDialog​(java.util.function.Consumer<Dialog> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onDialog(handler).
        Specified by:
        offDialog in interface Page
      • onDOMContentLoaded

        public void onDOMContentLoaded​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Emitted when the JavaScript DOMContentLoaded event is dispatched.
        Specified by:
        onDOMContentLoaded in interface Page
      • onDownload

        public void onDownload​(java.util.function.Consumer<Download> handler)
        Description copied from interface: Page
        Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.
        Specified by:
        onDownload in interface Page
      • offDownload

        public void offDownload​(java.util.function.Consumer<Download> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onDownload(handler).
        Specified by:
        offDownload in interface Page
      • onFileChooser

        public void onFileChooser​(java.util.function.Consumer<FileChooser> handler)
        Description copied from interface: Page
        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 using FileChooser.setFiles() that can be uploaded after that.
        
         page.onFileChooser(fileChooser -> {
           fileChooser.setFiles(Paths.get("/tmp/myfile.pdf"));
         });
         
        Specified by:
        onFileChooser in interface Page
      • onFrameAttached

        public void onFrameAttached​(java.util.function.Consumer<Frame> handler)
        Description copied from interface: Page
        Emitted when a frame is attached.
        Specified by:
        onFrameAttached in interface Page
      • onFrameDetached

        public void onFrameDetached​(java.util.function.Consumer<Frame> handler)
        Description copied from interface: Page
        Emitted when a frame is detached.
        Specified by:
        onFrameDetached in interface Page
      • onFrameNavigated

        public void onFrameNavigated​(java.util.function.Consumer<Frame> handler)
        Description copied from interface: Page
        Emitted when a frame is navigated to a new url.
        Specified by:
        onFrameNavigated in interface Page
      • onLoad

        public void onLoad​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Emitted when the JavaScript load event is dispatched.
        Specified by:
        onLoad in interface Page
      • offLoad

        public void offLoad​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onLoad(handler).
        Specified by:
        offLoad in interface Page
      • onPageError

        public void onPageError​(java.util.function.Consumer<java.lang.String> handler)
        Description copied from interface: Page
        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>");
         
        Specified by:
        onPageError in interface Page
      • offPageError

        public void offPageError​(java.util.function.Consumer<java.lang.String> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onPageError(handler).
        Specified by:
        offPageError in interface Page
      • onPopup

        public void onPopup​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Emitted when the page opens a new tab or window. This event is emitted in addition to the BrowserContext.onPage(), but only for popups relevant to this page.

        The earliest moment that page is available is when it has navigated to the initial url. For example, when opening a popup with window.open('http://example.com'), this event will fire when the network request to "http://example.com" is done and its response has started loading in the popup.

        
         Page popup = page.waitForPopup(() -> {
           page.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).

        Specified by:
        onPopup in interface Page
      • offPopup

        public void offPopup​(java.util.function.Consumer<Page> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onPopup(handler).
        Specified by:
        offPopup in interface Page
      • onRequest

        public void onRequest​(java.util.function.Consumer<Request> handler)
        Description copied from interface: Page
        Emitted when a page issues a request. The [request] object is read-only. In order to intercept and mutate requests, see Page.route() or BrowserContext.route().
        Specified by:
        onRequest in interface Page
      • offRequest

        public void offRequest​(java.util.function.Consumer<Request> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onRequest(handler).
        Specified by:
        offRequest in interface Page
      • onRequestFailed

        public void onRequestFailed​(java.util.function.Consumer<Request> handler)
        Description copied from interface: Page
        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 with Page.onRequestFailed(). A request will only be considered failed when the client cannot get an HTTP response from the server, e.g. due to network error net::ERR_FAILED.

        Specified by:
        onRequestFailed in interface Page
      • onRequestFinished

        public void onRequestFinished​(java.util.function.Consumer<Request> handler)
        Description copied from interface: Page
        Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished.
        Specified by:
        onRequestFinished in interface Page
      • onResponse

        public void onResponse​(java.util.function.Consumer<Response> handler)
        Description copied from interface: Page
        Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished.
        Specified by:
        onResponse in interface Page
      • offResponse

        public void offResponse​(java.util.function.Consumer<Response> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onResponse(handler).
        Specified by:
        offResponse in interface Page
      • onWebSocket

        public void onWebSocket​(java.util.function.Consumer<WebSocket> handler)
        Description copied from interface: Page
        Emitted when WebSocket request is sent.
        Specified by:
        onWebSocket in interface Page
      • offWebSocket

        public void offWebSocket​(java.util.function.Consumer<WebSocket> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onWebSocket(handler).
        Specified by:
        offWebSocket in interface Page
      • onWorker

        public void onWorker​(java.util.function.Consumer<Worker> handler)
        Description copied from interface: Page
        Emitted when a dedicated WebWorker is spawned by the page.
        Specified by:
        onWorker in interface Page
      • offWorker

        public void offWorker​(java.util.function.Consumer<Worker> handler)
        Description copied from interface: Page
        Removes handler that was previously added with onWorker(handler).
        Specified by:
        offWorker in interface Page
      • waitForClose

        public Page waitForClose​(Page.WaitForCloseOptions options,
                                 java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for the Page to close.
        Specified by:
        waitForClose in interface Page
        code - Callback that performs the action triggering the event.
      • waitForConsoleMessage

        public ConsoleMessage waitForConsoleMessage​(Page.WaitForConsoleMessageOptions options,
                                                    java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a ConsoleMessage to be logged by in the page. If predicate is provided, it passes ConsoleMessage value into the predicate function and waits for predicate(message) to return a truthy value. Will throw an error if the page is closed before the Page.onConsoleMessage() event is fired.
        Specified by:
        waitForConsoleMessage in interface Page
        code - Callback that performs the action triggering the event.
      • waitForDownload

        public Download waitForDownload​(Page.WaitForDownloadOptions options,
                                        java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a new Download. If predicate is provided, it passes Download value into the predicate function and waits for predicate(download) to return a truthy value. Will throw an error if the page is closed before the download event is fired.
        Specified by:
        waitForDownload in interface Page
        code - Callback that performs the action triggering the event.
      • waitForFileChooser

        public FileChooser waitForFileChooser​(Page.WaitForFileChooserOptions options,
                                              java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a new FileChooser to be created. If predicate is provided, it passes FileChooser value into the predicate function and waits for predicate(fileChooser) to return a truthy value. Will throw an error if the page is closed before the file chooser is opened.
        Specified by:
        waitForFileChooser in interface Page
        code - Callback that performs the action triggering the event.
      • waitForPopup

        public Page waitForPopup​(Page.WaitForPopupOptions options,
                                 java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a popup Page. If predicate is provided, it passes [Popup] value into the predicate function and waits for predicate(page) to return a truthy value. Will throw an error if the page is closed before the popup event is fired.
        Specified by:
        waitForPopup in interface Page
        code - Callback that performs the action triggering the event.
      • waitForWebSocket

        public WebSocket waitForWebSocket​(Page.WaitForWebSocketOptions options,
                                          java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a new WebSocket. If predicate is provided, it passes WebSocket value into the predicate function and waits for predicate(webSocket) to return a truthy value. Will throw an error if the page is closed before the WebSocket event is fired.
        Specified by:
        waitForWebSocket in interface Page
        code - Callback that performs the action triggering the event.
      • waitForWorker

        public Worker waitForWorker​(Page.WaitForWorkerOptions options,
                                    java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a new Worker. If predicate is provided, it passes Worker value into the predicate function and waits for predicate(worker) to return a truthy value. Will throw an error if the page is closed before the worker event is fired.
        Specified by:
        waitForWorker in interface Page
        code - Callback that performs the action triggering the event.
      • waitForEventWithTimeout

        private <T> T waitForEventWithTimeout​(PageImpl.EventType eventType,
                                              java.lang.Runnable code,
                                              java.util.function.Predicate<T> predicate,
                                              java.lang.Double timeout)
      • close

        public void close​(Page.CloseOptions options)
        Description copied from interface: Page
        If runBeforeUnload is false, does not run any unload handlers and waits for the page to be closed. If runBeforeUnload is true the method will run unload handlers, but will **not** wait for the page to close.

        By default, page.close() **does not** run beforeunload handlers.

        NOTE: if runBeforeUnload is passed as true, a beforeunload dialog might be summoned and should be handled manually via Page.onDialog() event.

        Specified by:
        close in interface Page
      • querySelector

        public ElementHandle querySelector​(java.lang.String selector,
                                           Page.QuerySelectorOptions options)
        Description copied from interface: Page
        The method finds an element matching the specified selector within the page. If no elements match the selector, the return value resolves to null. To wait for an element on the page, use Locator.waitFor().
        Specified by:
        querySelector in interface Page
        Parameters:
        selector - A selector to query for.
      • querySelectorAll

        public java.util.List<ElementHandle> querySelectorAll​(java.lang.String selector)
        Description copied from interface: Page
        The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].
        Specified by:
        querySelectorAll in interface Page
        Parameters:
        selector - A selector to query for.
      • evalOnSelector

        public java.lang.Object evalOnSelector​(java.lang.String selector,
                                               java.lang.String pageFunction,
                                               java.lang.Object arg,
                                               Page.EvalOnSelectorOptions options)
        Description copied from interface: Page
        The method finds an element matching the specified selector within the page and passes it as a first argument to expression. If no elements match the selector, the method throws an error. Returns the value of expression.

        If expression returns a Promise, then Page.evalOnSelector() would wait for the promise to resolve and return its value.

        **Usage**

        
         String searchValue = (String) page.evalOnSelector("#search", "el => el.value");
         String preloadHref = (String) page.evalOnSelector("link[rel=preload]", "el => el.href");
         String html = (String) page.evalOnSelector(".main-container", "(e, suffix) => e.outerHTML + suffix", "hello");
         
        Specified by:
        evalOnSelector in interface Page
        Parameters:
        selector - A selector to query for.
        pageFunction - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
      • evalOnSelectorAll

        public java.lang.Object evalOnSelectorAll​(java.lang.String selector,
                                                  java.lang.String pageFunction,
                                                  java.lang.Object arg)
        Description copied from interface: Page
        The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to expression. Returns the result of expression invocation.

        If expression returns a Promise, then Page.evalOnSelectorAll() would wait for the promise to resolve and return its value.

        **Usage**

        
         boolean divCounts = (boolean) page.evalOnSelectorAll("div", "(divs, min) => divs.length >= min", 10);
         
        Specified by:
        evalOnSelectorAll in interface Page
        Parameters:
        selector - A selector to query for.
        pageFunction - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
      • addInitScript

        public void addInitScript​(java.lang.String script)
        Description copied from interface: Page
        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.random before the page loads:

        
         // In your playwright script, assuming the preload.js file is in same directory
         page.addInitScript(Paths.get("./preload.js"));
         

        NOTE: The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and Page.addInitScript() is not defined.

        Specified by:
        addInitScript in interface Page
        Parameters:
        script - Script to be evaluated in all pages in the browser context.
      • addInitScript

        public void addInitScript​(java.nio.file.Path path)
        Description copied from interface: Page
        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.random before the page loads:

        
         // In your playwright script, assuming the preload.js file is in same directory
         page.addInitScript(Paths.get("./preload.js"));
         

        NOTE: The order of evaluation of multiple scripts installed via BrowserContext.addInitScript() and Page.addInitScript() is not defined.

        Specified by:
        addInitScript in interface Page
        Parameters:
        path - Script to be evaluated in all pages in the browser context.
      • addInitScriptImpl

        private void addInitScriptImpl​(java.lang.String script)
      • addScriptTag

        public ElementHandle addScriptTag​(Page.AddScriptTagOptions options)
        Description copied from interface: Page
        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.
        Specified by:
        addScriptTag in interface Page
      • addStyleTag

        public ElementHandle addStyleTag​(Page.AddStyleTagOptions options)
        Description copied from interface: Page
        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.
        Specified by:
        addStyleTag in interface Page
      • bringToFront

        public void bringToFront()
        Description copied from interface: Page
        Brings page to front (activates tab).
        Specified by:
        bringToFront in interface Page
      • check

        public void check​(java.lang.String selector,
                          Page.CheckOptions options)
        Description copied from interface: Page
        This method checks an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. 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.
        3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        4. Scroll the element into view if needed.
        5. Use Page.mouse() to click in the center of the element.
        6. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
        7. 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 a TimeoutError. Passing zero timeout disables this.

        Specified by:
        check in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • click

        public void click​(java.lang.String selector,
                          Page.ClickOptions options)
        Description copied from interface: Page
        This method clicks an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        3. Scroll the element into view if needed.
        4. Use Page.mouse() to click in the center of the element, or the specified position.
        5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

        When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

        Specified by:
        click in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • content

        public java.lang.String content()
        Description copied from interface: Page
        Gets the full HTML contents of the page, including the doctype.
        Specified by:
        content in interface Page
      • context

        public BrowserContextImpl context()
        Description copied from interface: Page
        Get the browser context that the page belongs to.
        Specified by:
        context in interface Page
      • dblclick

        public void dblclick​(java.lang.String selector,
                             Page.DblclickOptions options)
        Description copied from interface: Page
        This method double clicks an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        3. Scroll the element into view if needed.
        4. Use Page.mouse() to double click in the center of the element, or the specified position.
        5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set. Note that if the first click of the dblclick() triggers a navigation event, this method will throw.

        When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

        NOTE: page.dblclick() dispatches two click events and a single dblclick event.

        Specified by:
        dblclick in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • dispatchEvent

        public void dispatchEvent​(java.lang.String selector,
                                  java.lang.String type,
                                  java.lang.Object eventInit,
                                  Page.DispatchEventOptions options)
        Description copied from interface: Page
        The snippet below dispatches the click event on the element. Regardless of the visibility state of the element, click is 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 with eventInit properties and dispatches it on the element. Events are composed, cancelable and bubble by default.

        Since eventInit is event-specific, please refer to the events documentation for the lists of initial properties:

        You can also specify JSHandle as the property value if you want live objects to be passed into the event:

        
         // Note you can only create DataTransfer in Chromium and Firefox
         JSHandle dataTransfer = page.evaluateHandle("() => new DataTransfer()");
         Map<String, Object> arg = new HashMap<>();
         arg.put("dataTransfer", dataTransfer);
         page.dispatchEvent("#source", "dragstart", arg);
         
        Specified by:
        dispatchEvent in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        type - DOM event type: "click", "dragstart", etc.
        eventInit - Optional event-specific initialization properties.
      • emulateMedia

        public void emulateMedia​(Page.EmulateMediaOptions options)
        Description copied from interface: Page
        This method changes the CSS media type through the media argument, and/or the "prefers-colors-scheme" media feature, using the colorScheme argument.

        **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");
         // → false
         
        
         page.emulateMedia(new Page.EmulateMediaOptions().setColorScheme(ColorScheme.DARK));
         page.evaluate("() => matchMedia('(prefers-color-scheme: dark)').matches");
         // → true
         page.evaluate("() => matchMedia('(prefers-color-scheme: light)').matches");
         // → false
         page.evaluate("() => matchMedia('(prefers-color-scheme: no-preference)').matches");
         // → false
         
        Specified by:
        emulateMedia in interface Page
      • evaluate

        public java.lang.Object evaluate​(java.lang.String expression,
                                         java.lang.Object arg)
        Description copied from interface: Page
        Returns the value of the expression invocation.

        If the function passed to the Page.evaluate() returns a Promise, then Page.evaluate() would wait for the promise to resolve and return its value.

        If the function passed to the Page.evaluate() returns a non-[Serializable] value, then Page.evaluate() resolves to undefined. Playwright also supports transferring some additional values that are not serializable by JSON: -0, NaN, Infinity, -Infinity.

        **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"
         

        ElementHandle instances can be passed as an argument to the Page.evaluate():

        
         ElementHandle bodyHandle = page.evaluate("document.body");
         String html = (String) page.evaluate("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(bodyHandle, "hello"));
         bodyHandle.dispose();
         
        Specified by:
        evaluate in interface Page
        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 to expression.
      • evaluateHandle

        public JSHandle evaluateHandle​(java.lang.String pageFunction,
                                       java.lang.Object arg)
        Description copied from interface: Page
        Returns the value of the expression invocation as a JSHandle.

        The only difference between Page.evaluate() and Page.evaluateHandle() is that Page.evaluateHandle() returns JSHandle.

        If the function passed to the Page.evaluateHandle() returns a Promise, then Page.evaluateHandle() would wait for the promise to resolve and return its value.

        **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".
         

        JSHandle instances can be passed as an argument to the Page.evaluateHandle():

        
         JSHandle aHandle = page.evaluateHandle("() => document.body");
         JSHandle resultHandle = page.evaluateHandle("([body, suffix]) => body.innerHTML + suffix", Arrays.asList(aHandle, "hello"));
         System.out.println(resultHandle.jsonValue());
         resultHandle.dispose();
         
        Specified by:
        evaluateHandle in interface Page
        Parameters:
        pageFunction - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
      • exposeBinding

        public void exposeBinding​(java.lang.String name,
                                  BindingCallback playwrightBinding,
                                  Page.ExposeBindingOptions options)
        Description copied from interface: Page
        The method adds a function called name on the window object of every frame in this page. When called, the function executes callback and returns a Promise which resolves to the return value of callback. If the callback returns a Promise, it will be awaited.

        The first argument of the callback function contains information about the caller: { browserContext: BrowserContext, page: Page, frame: Frame }.

        See BrowserContext.exposeBinding() for the context-wide version.

        NOTE: Functions installed via Page.exposeBinding() survive navigations.

        **Usage**

        An example of exposing page URL to all frames in a page:

        
         import com.microsoft.playwright.*;
        
         public class Example {
           public static void main(String[] args) {
             try (Playwright playwright = Playwright.create()) {
               BrowserType webkit = playwright.webkit();
               Browser browser = webkit.launch({ headless: false });
               BrowserContext context = browser.newContext();
               Page page = context.newPage();
               page.exposeBinding("pageURL", (source, args) -> source.page().url());
               page.setContent("<script>\n" +
                 "  async function onClick() {\n" +
                 "    document.querySelector('div').textContent = await window.pageURL();\n" +
                 "  }\n" +
                 "</script>\n" +
                 "<button onclick=\"onClick()\">Click me</button>\n" +
                 "<div></div>");
               page.click("button");
             }
           }
         }
         

        An example of passing an element handle:

        
         page.exposeBinding("clicked", (source, args) -> {
           ElementHandle element = (ElementHandle) args[0];
           System.out.println(element.textContent());
           return null;
         }, new Page.ExposeBindingOptions().setHandle(true));
         page.setContent("" +
           "<script>\n" +
           "  document.addEventListener('click', event => window.clicked(event.target));\n" +
           "</script>\n" +
           "<div>Click me</div>\n" +
           "<div>Or click me</div>\n");
         
        Specified by:
        exposeBinding in interface Page
        Parameters:
        name - Name of the function on the window object.
        playwrightBinding - Callback function that will be called in the Playwright's context.
      • exposeFunction

        public void exposeFunction​(java.lang.String name,
                                   FunctionCallback playwrightFunction)
        Description copied from interface: Page
        The method adds a function called name on the window object of every frame in the page. When called, the function executes callback and returns a Promise which resolves to the return value of callback.

        If the callback returns a Promise, it will be awaited.

        See BrowserContext.exposeFunction() for context-wide exposed function.

        NOTE: Functions installed via Page.exposeFunction() survive navigations.

        **Usage**

        An example of adding a sha256 function to the page:

        
         import com.microsoft.playwright.*;
        
         import java.nio.charset.StandardCharsets;
         import java.security.MessageDigest;
         import java.security.NoSuchAlgorithmException;
         import java.util.Base64;
        
         public class Example {
           public static void main(String[] args) {
             try (Playwright playwright = Playwright.create()) {
               BrowserType webkit = playwright.webkit();
               Browser browser = webkit.launch({ headless: false });
               Page page = browser.newPage();
               page.exposeFunction("sha256", args -> {
                 String text = (String) args[0];
                 MessageDigest crypto;
                 try {
                   crypto = MessageDigest.getInstance("SHA-256");
                 } catch (NoSuchAlgorithmException e) {
                   return null;
                 }
                 byte[] token = crypto.digest(text.getBytes(StandardCharsets.UTF_8));
                 return Base64.getEncoder().encodeToString(token);
               });
               page.setContent("<script>\n" +
                 "  async function onClick() {\n" +
                 "    document.querySelector('div').textContent = await window.sha256('PLAYWRIGHT');\n" +
                 "  }\n" +
                 "</script>\n" +
                 "<button onclick=\"onClick()\">Click me</button>\n" +
                 "<div></div>\n");
               page.click("button");
             }
           }
         }
         
        Specified by:
        exposeFunction in interface Page
        Parameters:
        name - Name of the function on the window object
        playwrightFunction - Callback function which will be called in Playwright's context.
      • fill

        public void fill​(java.lang.String selector,
                         java.lang.String value,
                         Page.FillOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, focuses the element, fills it and triggers an input event after filling. Note that you can pass an empty string to clear the input field.

        If the target element is not an <input>, <textarea> or [contenteditable] element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be filled instead.

        To send fine-grained keyboard events, use Locator.pressSequentially().

        Specified by:
        fill in interface Page
        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.
      • focus

        public void focus​(java.lang.String selector,
                          Page.FocusOptions options)
        Description copied from interface: Page
        This method fetches an element with selector and focuses it. If there's no element matching selector, the method waits until a matching element appears in the DOM.
        Specified by:
        focus in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • frame

        public Frame frame​(java.lang.String name)
        Description copied from interface: Page
        Returns frame matching the specified criteria. Either name or url must be specified.

        **Usage**

        
         Frame frame = page.frame("frame-name");
         
        
         Frame frame = page.frameByUrl(Pattern.compile(".*domain.*");
         
        Specified by:
        frame in interface Page
        Parameters:
        name - Frame name specified in the iframe's name attribute.
      • frameByUrl

        public Frame frameByUrl​(java.lang.String glob)
        Description copied from interface: Page
        Returns frame with matching URL.
        Specified by:
        frameByUrl in interface Page
        Parameters:
        glob - A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.
      • frameByUrl

        public Frame frameByUrl​(java.util.regex.Pattern pattern)
        Description copied from interface: Page
        Returns frame with matching URL.
        Specified by:
        frameByUrl in interface Page
        Parameters:
        pattern - A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.
      • frameByUrl

        public Frame frameByUrl​(java.util.function.Predicate<java.lang.String> predicate)
        Description copied from interface: Page
        Returns frame with matching URL.
        Specified by:
        frameByUrl in interface Page
        Parameters:
        predicate - A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.
      • frameLocator

        public FrameLocator frameLocator​(java.lang.String selector)
        Description copied from interface: Page
        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();
         
        Specified by:
        frameLocator in interface Page
        Parameters:
        selector - A selector to use when resolving DOM element.
      • frames

        public java.util.List<Frame> frames()
        Description copied from interface: Page
        An array of all frames attached to the page.
        Specified by:
        frames in interface Page
      • getAttribute

        public java.lang.String getAttribute​(java.lang.String selector,
                                             java.lang.String name,
                                             Page.GetAttributeOptions options)
        Description copied from interface: Page
        Returns element attribute value.
        Specified by:
        getAttribute in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        name - Attribute name to get the value for.
      • getByAltText

        public Locator getByAltText​(java.lang.String text,
                                    Page.GetByAltTextOptions options)
        Description copied from interface: Page
        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();
         
        Specified by:
        getByAltText in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByAltText

        public Locator getByAltText​(java.util.regex.Pattern text,
                                    Page.GetByAltTextOptions options)
        Description copied from interface: Page
        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();
         
        Specified by:
        getByAltText in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByLabel

        public Locator getByLabel​(java.lang.String text,
                                  Page.GetByLabelOptions options)
        Description copied from interface: Page
        Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

        **Usage**

        For example, this method will find inputs by label "Username" and "Password" in the following DOM:

        
         page.getByLabel("Username").fill("john");
         page.getByLabel("Password").fill("secret");
         
        Specified by:
        getByLabel in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByLabel

        public Locator getByLabel​(java.util.regex.Pattern text,
                                  Page.GetByLabelOptions options)
        Description copied from interface: Page
        Allows locating input elements by the text of the associated <label> or aria-labelledby element, or by the aria-label attribute.

        **Usage**

        For example, this method will find inputs by label "Username" and "Password" in the following DOM:

        
         page.getByLabel("Username").fill("john");
         page.getByLabel("Password").fill("secret");
         
        Specified by:
        getByLabel in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByPlaceholder

        public Locator getByPlaceholder​(java.lang.String text,
                                        Page.GetByPlaceholderOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        getByPlaceholder in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByPlaceholder

        public Locator getByPlaceholder​(java.util.regex.Pattern text,
                                        Page.GetByPlaceholderOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        getByPlaceholder in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByRole

        public Locator getByRole​(AriaRole role,
                                 Page.GetByRoleOptions options)
        Description copied from interface: Page
        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 role and/or aria-* attributes to default values.

        Specified by:
        getByRole in interface Page
        Parameters:
        role - Required aria role.
      • getByTestId

        public Locator getByTestId​(java.lang.String testId)
        Description copied from interface: Page
        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-testid attribute is used as a test id. Use Selectors.setTestIdAttribute() to configure a different test id attribute if necessary.

        Specified by:
        getByTestId in interface Page
        Parameters:
        testId - Id to locate the element by.
      • getByTestId

        public Locator getByTestId​(java.util.regex.Pattern testId)
        Description copied from interface: Page
        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-testid attribute is used as a test id. Use Selectors.setTestIdAttribute() to configure a different test id attribute if necessary.

        Specified by:
        getByTestId in interface Page
        Parameters:
        testId - Id to locate the element by.
      • getByText

        public Locator getByText​(java.lang.String text,
                                 Page.GetByTextOptions options)
        Description copied from interface: Page
        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 button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.

        Specified by:
        getByText in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByText

        public Locator getByText​(java.util.regex.Pattern text,
                                 Page.GetByTextOptions options)
        Description copied from interface: Page
        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 button and submit are matched by their value instead of the text content. For example, locating by text "Log in" matches <input type=button value="Log in">.

        Specified by:
        getByText in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByTitle

        public Locator getByTitle​(java.lang.String text,
                                  Page.GetByTitleOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        getByTitle in interface Page
        Parameters:
        text - Text to locate the element for.
      • getByTitle

        public Locator getByTitle​(java.util.regex.Pattern text,
                                  Page.GetByTitleOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        getByTitle in interface Page
        Parameters:
        text - Text to locate the element for.
      • goBack

        public Response goBack​(Page.GoBackOptions options)
        Description copied from interface: Page
        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, returns null.

        Navigate to the previous page in history.

        Specified by:
        goBack in interface Page
      • goForward

        public Response goForward​(Page.GoForwardOptions options)
        Description copied from interface: Page
        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, returns null.

        Navigate to the next page in history.

        Specified by:
        goForward in interface Page
      • navigate

        public ResponseImpl navigate​(java.lang.String url,
                                     Page.NavigateOptions options)
        Description copied from interface: Page
        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 timeout is 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:blank or navigation to the same URL with a different hash, which would succeed and return null.

        NOTE: Headless mode doesn't support navigation to a PDF document. See the upstream issue.

        Specified by:
        navigate in interface Page
        Parameters:
        url - URL to navigate page to. The url should include scheme, e.g. https://. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
      • hover

        public void hover​(java.lang.String selector,
                          Page.HoverOptions options)
        Description copied from interface: Page
        This method hovers over an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        3. Scroll the element into view if needed.
        4. Use Page.mouse() to hover over the center of the element, or the specified position.
        5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

        When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

        Specified by:
        hover in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • dragAndDrop

        public void dragAndDrop​(java.lang.String source,
                                java.lang.String target,
                                Page.DragAndDropOptions options)
        Description copied from interface: Page
        This method drags the source element to the target element. It will first move to the source element, perform a mousedown, then move to the target element and perform a mouseup.

        **Usage**

        
         page.dragAndDrop("#source", '#target');
         // or specify exact positions relative to the top-left corners of the elements:
         page.dragAndDrop("#source", '#target', new Page.DragAndDropOptions()
           .setSourcePosition(34, 7).setTargetPosition(10, 20));
         
        Specified by:
        dragAndDrop in interface Page
        Parameters:
        source - A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
        target - A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
      • innerHTML

        public java.lang.String innerHTML​(java.lang.String selector,
                                          Page.InnerHTMLOptions options)
        Description copied from interface: Page
        Returns element.innerHTML.
        Specified by:
        innerHTML in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • innerText

        public java.lang.String innerText​(java.lang.String selector,
                                          Page.InnerTextOptions options)
        Description copied from interface: Page
        Returns element.innerText.
        Specified by:
        innerText in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • inputValue

        public java.lang.String inputValue​(java.lang.String selector,
                                           Page.InputValueOptions options)
        Description copied from interface: Page
        Returns input.value for the selected <input> or <textarea> or <select> element.

        Throws for non-input elements. However, if the element is inside the <label> element that has an associated control, returns the value of the control.

        Specified by:
        inputValue in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • isChecked

        public boolean isChecked​(java.lang.String selector,
                                 Page.IsCheckedOptions options)
        Description copied from interface: Page
        Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
        Specified by:
        isChecked in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • isClosed

        public boolean isClosed()
        Description copied from interface: Page
        Indicates that the page has been closed.
        Specified by:
        isClosed in interface Page
      • isDisabled

        public boolean isDisabled​(java.lang.String selector,
                                  Page.IsDisabledOptions options)
        Description copied from interface: Page
        Returns whether the element is disabled, the opposite of enabled.
        Specified by:
        isDisabled in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • isEditable

        public boolean isEditable​(java.lang.String selector,
                                  Page.IsEditableOptions options)
        Description copied from interface: Page
        Returns whether the element is editable.
        Specified by:
        isEditable in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • isEnabled

        public boolean isEnabled​(java.lang.String selector,
                                 Page.IsEnabledOptions options)
        Description copied from interface: Page
        Returns whether the element is enabled.
        Specified by:
        isEnabled in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • isHidden

        public boolean isHidden​(java.lang.String selector,
                                Page.IsHiddenOptions options)
        Description copied from interface: Page
        Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.
        Specified by:
        isHidden in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • isVisible

        public boolean isVisible​(java.lang.String selector,
                                 Page.IsVisibleOptions options)
        Description copied from interface: Page
        Returns whether the element is visible. selector that does not match any elements is considered not visible.
        Specified by:
        isVisible in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • locator

        public Locator locator​(java.lang.String selector,
                               Page.LocatorOptions options)
        Description copied from interface: Page
        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.

        Learn more about locators.

        Specified by:
        locator in interface Page
        Parameters:
        selector - A selector to use when resolving DOM element.
      • mainFrame

        public Frame mainFrame()
        Description copied from interface: Page
        The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
        Specified by:
        mainFrame in interface Page
      • mouse

        public Mouse mouse()
        Specified by:
        mouse in interface Page
      • opener

        public PageImpl opener()
        Description copied from interface: Page
        Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.
        Specified by:
        opener in interface Page
      • pause

        public void pause()
        Description copied from interface: Page
        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 call playwright.resume() in the DevTools console.

        User can inspect selectors or perform manual steps while paused. Resume will continue running the original script from the place it was paused.

        NOTE: This method requires Playwright to be started in a headed mode, with a falsy headless value in the BrowserType.launch().

        Specified by:
        pause in interface Page
      • pdf

        public byte[] pdf​(Page.PdfOptions options)
        Description copied from interface: Page
        Returns the PDF buffer.

        NOTE: Generating a pdf is currently only supported in Chromium headless.

        page.pdf() generates a pdf of the page with print css media. To generate a pdf with screen media, call Page.emulateMedia() before calling page.pdf():

        NOTE: By default, page.pdf() generates a pdf with modified colors for printing. Use the -webkit-print-color-adjust property to force rendering of exact colors.

        **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, and margin options accept values labeled with units. Unlabeled values are treated as pixels.

        A few examples:

        • page.pdf({width: 100}) - prints with width set to 100 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 format options 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: headerTemplate and footerTemplate markup have the following limitations: > 1. Script tags inside templates are not evaluated. > 2. Page styles are not visible inside templates.

        Specified by:
        pdf in interface Page
      • press

        public void press​(java.lang.String selector,
                          java.lang.String key,
                          Page.PressOptions options)
        Description copied from interface: Page
        Focuses the element, and then uses Keyboard.down() and Keyboard.up().

        key can specify the intended keyboardEvent.key value or a single character to generate the text for. A superset of the key values can be found here. Examples of the keys are:

        F1 - F12, Digit0- Digit9, KeyA- KeyZ, Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape, ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight, ArrowUp, etc.

        Following modification shortcuts are also supported: Shift, Control, Alt, Meta, ShiftLeft.

        Holding down Shift will type the text that corresponds to the key in the upper case.

        If key is a single character, it is case-sensitive, so the values a and A will generate different respective texts.

        Shortcuts such as key: "Control+o" or key: "Control+Shift+T" are supported as well. When specified with the modifier, modifier is pressed and being held while the subsequent key is being pressed.

        **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" )));
         
        Specified by:
        press in interface Page
        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 as ArrowLeft or a.
      • reload

        public Response reload​(Page.ReloadOptions options)
        Description copied from interface: Page
        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.
        Specified by:
        reload in interface Page
      • route

        public void route​(java.lang.String url,
                          java.util.function.Consumer<Route> handler,
                          Page.RouteOptions options)
        Description copied from interface: Page
        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 setting Browser.newContext.serviceWorkers to "block".

        **Usage**

        An example of a naive handler that aborts all image requests:

        
         Page page = browser.newPage();
         page.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
         page.navigate("https://example.com");
         browser.close();
         

        or the same snippet using a regex pattern instead:

        
         Page page = browser.newPage();
         page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
         page.navigate("https://example.com");
         browser.close();
         

        It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

        
         page.route("/api/**", route -> {
           if (route.request().postData().contains("my-string"))
             route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
           else
             route.resume();
         });
         

        Page routes take precedence over browser context routes (set up with BrowserContext.route()) when request matches both handlers.

        To remove a route with its handler you can use Page.unroute().

        NOTE: Enabling routing disables http cache.

        Specified by:
        route in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        handler - handler function to route the request.
      • route

        public void route​(java.util.regex.Pattern url,
                          java.util.function.Consumer<Route> handler,
                          Page.RouteOptions options)
        Description copied from interface: Page
        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 setting Browser.newContext.serviceWorkers to "block".

        **Usage**

        An example of a naive handler that aborts all image requests:

        
         Page page = browser.newPage();
         page.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
         page.navigate("https://example.com");
         browser.close();
         

        or the same snippet using a regex pattern instead:

        
         Page page = browser.newPage();
         page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
         page.navigate("https://example.com");
         browser.close();
         

        It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

        
         page.route("/api/**", route -> {
           if (route.request().postData().contains("my-string"))
             route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
           else
             route.resume();
         });
         

        Page routes take precedence over browser context routes (set up with BrowserContext.route()) when request matches both handlers.

        To remove a route with its handler you can use Page.unroute().

        NOTE: Enabling routing disables http cache.

        Specified by:
        route in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        handler - handler function to route the request.
      • route

        public void route​(java.util.function.Predicate<java.lang.String> url,
                          java.util.function.Consumer<Route> handler,
                          Page.RouteOptions options)
        Description copied from interface: Page
        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 setting Browser.newContext.serviceWorkers to "block".

        **Usage**

        An example of a naive handler that aborts all image requests:

        
         Page page = browser.newPage();
         page.route("**\/*.{png,jpg,jpeg}", route -> route.abort());
         page.navigate("https://example.com");
         browser.close();
         

        or the same snippet using a regex pattern instead:

        
         Page page = browser.newPage();
         page.route(Pattern.compile("(\\.png$)|(\\.jpg$)"),route -> route.abort());
         page.navigate("https://example.com");
         browser.close();
         

        It is possible to examine the request to decide the route action. For example, mocking all requests that contain some post data, and leaving all other requests as is:

        
         page.route("/api/**", route -> {
           if (route.request().postData().contains("my-string"))
             route.fulfill(new Route.FulfillOptions().setBody("mocked-data"));
           else
             route.resume();
         });
         

        Page routes take precedence over browser context routes (set up with BrowserContext.route()) when request matches both handlers.

        To remove a route with its handler you can use Page.unroute().

        NOTE: Enabling routing disables http cache.

        Specified by:
        route in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        handler - handler function to route the request.
      • routeFromHAR

        public void routeFromHAR​(java.nio.file.Path har,
                                 Page.RouteFromHAROptions options)
        Description copied from interface: Page
        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.serviceWorkers to "block".

        Specified by:
        routeFromHAR in interface Page
        Parameters:
        har - Path to a HAR file with prerecorded network data. If path is a relative path, then it is resolved relative to the current working directory.
      • screenshot

        public byte[] screenshot​(Page.ScreenshotOptions options)
        Description copied from interface: Page
        Returns the buffer with the captured screenshot.
        Specified by:
        screenshot in interface Page
      • selectOption

        public java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                             java.lang.String value,
                                                             Page.SelectOptionOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

        Returns the array of option values that have been successfully selected.

        Triggers a change and input event once all the provided options have been selected.

        **Usage**

        
         // Single selection matching the value or label
         page.selectOption("select#colors", "blue");
         // single selection matching both the value and the label
         page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
         // multiple selection
         page.selectOption("select#colors", new String[] {"red", "green", "blue"});
         
        Specified by:
        selectOption in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        value - Options to select. If the <select> has the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.
      • selectOption

        public java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                             ElementHandle value,
                                                             Page.SelectOptionOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

        Returns the array of option values that have been successfully selected.

        Triggers a change and input event once all the provided options have been selected.

        **Usage**

        
         // Single selection matching the value or label
         page.selectOption("select#colors", "blue");
         // single selection matching both the value and the label
         page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
         // multiple selection
         page.selectOption("select#colors", new String[] {"red", "green", "blue"});
         
        Specified by:
        selectOption in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        value - Options to select. If the <select> has the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.
      • selectOption

        public java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                             java.lang.String[] values,
                                                             Page.SelectOptionOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

        Returns the array of option values that have been successfully selected.

        Triggers a change and input event once all the provided options have been selected.

        **Usage**

        
         // Single selection matching the value or label
         page.selectOption("select#colors", "blue");
         // single selection matching both the value and the label
         page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
         // multiple selection
         page.selectOption("select#colors", new String[] {"red", "green", "blue"});
         
        Specified by:
        selectOption in interface Page
        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 the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.
      • selectOption

        public java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                             SelectOption value,
                                                             Page.SelectOptionOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

        Returns the array of option values that have been successfully selected.

        Triggers a change and input event once all the provided options have been selected.

        **Usage**

        
         // Single selection matching the value or label
         page.selectOption("select#colors", "blue");
         // single selection matching both the value and the label
         page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
         // multiple selection
         page.selectOption("select#colors", new String[] {"red", "green", "blue"});
         
        Specified by:
        selectOption in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        value - Options to select. If the <select> has the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.
      • selectOption

        public java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                             SelectOption[] values,
                                                             Page.SelectOptionOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

        Returns the array of option values that have been successfully selected.

        Triggers a change and input event once all the provided options have been selected.

        **Usage**

        
         // Single selection matching the value or label
         page.selectOption("select#colors", "blue");
         // single selection matching both the value and the label
         page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
         // multiple selection
         page.selectOption("select#colors", new String[] {"red", "green", "blue"});
         
        Specified by:
        selectOption in interface Page
        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 the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.
      • selectOption

        public java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                             ElementHandle[] values,
                                                             Page.SelectOptionOptions options)
        Description copied from interface: Page
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        If the target element is not a <select> element, this method throws an error. However, if the element is inside the <label> element that has an associated control, the control will be used instead.

        Returns the array of option values that have been successfully selected.

        Triggers a change and input event once all the provided options have been selected.

        **Usage**

        
         // Single selection matching the value or label
         page.selectOption("select#colors", "blue");
         // single selection matching both the value and the label
         page.selectOption("select#colors", new SelectOption().setLabel("Blue"));
         // multiple selection
         page.selectOption("select#colors", new String[] {"red", "green", "blue"});
         
        Specified by:
        selectOption in interface Page
        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 the multiple attribute, all matching options are selected, otherwise only the first option matching one of the passed options is selected. String values are matching both values and labels. Option is considered matching if all specified properties match.
      • setChecked

        public void setChecked​(java.lang.String selector,
                               boolean checked,
                               Page.SetCheckedOptions options)
        Description copied from interface: Page
        This method checks or unchecks an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. Ensure that matched element is a checkbox or a radio input. If not, this method throws.
        3. If the element already has the right checked state, this method returns immediately.
        4. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        5. Scroll the element into view if needed.
        6. Use Page.mouse() to click in the center of the element.
        7. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
        8. 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 a TimeoutError. Passing zero timeout disables this.

        Specified by:
        setChecked in interface Page
        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.
      • setContent

        public void setContent​(java.lang.String html,
                               Page.SetContentOptions options)
        Description copied from interface: Page
        This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
        Specified by:
        setContent in interface Page
        Parameters:
        html - HTML markup to assign to the page.
      • setExtraHTTPHeaders

        public void setExtraHTTPHeaders​(java.util.Map<java.lang.String,​java.lang.String> headers)
        Description copied from interface: Page
        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.

        Specified by:
        setExtraHTTPHeaders in interface Page
        Parameters:
        headers - An object containing additional HTTP headers to be sent with every request. All header values must be strings.
      • setInputFiles

        public void setInputFiles​(java.lang.String selector,
                                  java.nio.file.Path files,
                                  Page.SetInputFilesOptions options)
        Description copied from interface: Page
        Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

        This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

        Specified by:
        setInputFiles in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • setInputFiles

        public void setInputFiles​(java.lang.String selector,
                                  java.nio.file.Path[] files,
                                  Page.SetInputFilesOptions options)
        Description copied from interface: Page
        Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

        This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

        Specified by:
        setInputFiles in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • setInputFiles

        public void setInputFiles​(java.lang.String selector,
                                  FilePayload files,
                                  Page.SetInputFilesOptions options)
        Description copied from interface: Page
        Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

        This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

        Specified by:
        setInputFiles in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • setInputFiles

        public void setInputFiles​(java.lang.String selector,
                                  FilePayload[] files,
                                  Page.SetInputFilesOptions options)
        Description copied from interface: Page
        Sets the value of the file input to these file paths or files. If some of the filePaths are relative paths, then they are resolved relative to the current working directory. For empty array, clears the selected files.

        This method expects selector to point to an input element. However, if the element is inside the <label> element that has an associated control, targets the control instead.

        Specified by:
        setInputFiles in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • setViewportSize

        public void setViewportSize​(int width,
                                    int height)
        Description copied from interface: Page
        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 reset screen size, use Browser.newContext() with screen and viewport parameters if you need better control of these properties.

        **Usage**

        
         Page page = browser.newPage();
         page.setViewportSize(640, 480);
         page.navigate("https://example.com");
         
        Specified by:
        setViewportSize in interface Page
      • tap

        public void tap​(java.lang.String selector,
                        Page.TapOptions options)
        Description copied from interface: Page
        This method taps an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        3. Scroll the element into view if needed.
        4. Use Page.touchscreen() to tap the center of the element, or the specified position.
        5. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.

        When all steps combined have not finished during the specified timeout, this method throws a TimeoutError. Passing zero timeout disables this.

        NOTE: Page.tap() the method will throw if hasTouch option of the browser context is false.

        Specified by:
        tap in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • textContent

        public java.lang.String textContent​(java.lang.String selector,
                                            Page.TextContentOptions options)
        Description copied from interface: Page
        Returns element.textContent.
        Specified by:
        textContent in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • title

        public java.lang.String title()
        Description copied from interface: Page
        Returns the page's title.
        Specified by:
        title in interface Page
      • type

        public void type​(java.lang.String selector,
                         java.lang.String text,
                         Page.TypeOptions options)
        Specified by:
        type in interface Page
        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.
      • uncheck

        public void uncheck​(java.lang.String selector,
                            Page.UncheckOptions options)
        Description copied from interface: Page
        This method unchecks an element matching selector by performing the following steps:
        1. Find an element matching selector. If there is none, wait until a matching element is attached to the DOM.
        2. 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.
        3. Wait for actionability checks on the matched element, unless force option is set. If the element is detached during the checks, the whole action is retried.
        4. Scroll the element into view if needed.
        5. Use Page.mouse() to click in the center of the element.
        6. Wait for initiated navigations to either succeed or fail, unless noWaitAfter option is set.
        7. 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 a TimeoutError. Passing zero timeout disables this.

        Specified by:
        uncheck in interface Page
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
      • unroute

        public void unroute​(java.lang.String url,
                            java.util.function.Consumer<Route> handler)
        Description copied from interface: Page
        Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
        Specified by:
        unroute in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
        handler - Optional handler function to route the request.
      • unroute

        public void unroute​(java.util.regex.Pattern url,
                            java.util.function.Consumer<Route> handler)
        Description copied from interface: Page
        Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
        Specified by:
        unroute in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
        handler - Optional handler function to route the request.
      • unroute

        public void unroute​(java.util.function.Predicate<java.lang.String> url,
                            java.util.function.Consumer<Route> handler)
        Description copied from interface: Page
        Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
        Specified by:
        unroute in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
        handler - Optional handler function to route the request.
      • unroute

        private void unroute​(UrlMatcher matcher,
                             java.util.function.Consumer<Route> handler)
      • updateInterceptionPatterns

        private void updateInterceptionPatterns()
      • url

        public java.lang.String url()
        Specified by:
        url in interface Page
      • forceVideo

        private VideoImpl forceVideo()
      • video

        public VideoImpl video()
        Description copied from interface: Page
        Video object associated with this page.
        Specified by:
        video in interface Page
      • createWaitableNavigationTimeout

        <T> Waitable<T> createWaitableNavigationTimeout​(java.lang.Double timeout)
      • createWaitableTimeout

        <T> Waitable<T> createWaitableTimeout​(java.lang.Double timeout)
      • waitForFunction

        public JSHandle waitForFunction​(java.lang.String pageFunction,
                                        java.lang.Object arg,
                                        Page.WaitForFunctionOptions options)
        Description copied from interface: Page
        Returns when the expression returns a truthy value. It resolves to a JSHandle of the truthy value.

        **Usage**

        The Page.waitForFunction() can be used to observe viewport size change:

        
         import com.microsoft.playwright.*;
        
         public class Example {
           public static void main(String[] args) {
             try (Playwright playwright = Playwright.create()) {
               BrowserType webkit = playwright.webkit();
               Browser browser = webkit.launch();
               Page page = browser.newPage();
               page.setViewportSize(50,  50);
               page.waitForFunction("() => window.innerWidth < 100");
               browser.close();
             }
           }
         }
         

        To pass an argument to the predicate of Page.waitForFunction() function:

        
         String selector = ".foo";
         page.waitForFunction("selector => !!document.querySelector(selector)", selector);
         
        Specified by:
        waitForFunction in interface Page
        Parameters:
        pageFunction - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
      • waitForLoadState

        public void waitForLoadState​(LoadState state,
                                     Page.WaitForLoadStateOptions options)
        Description copied from interface: Page
        Returns when the required load state has been reached.

        This resolves when the page reaches a required load state, load by default. The navigation must have been committed when this method is called. If current document has already reached the required state, resolves immediately.

        **Usage**

        
         page.getByRole(AriaRole.BUTTON).click(); // Click triggers navigation.
         page.waitForLoadState(); // The promise resolves after "load" event.
         
        
         Page popup = page.waitForPopup(() -> {
           page.getByRole(AriaRole.BUTTON).click(); // Click triggers a popup.
         });
         // Wait for the "DOMContentLoaded" event
         popup.waitForLoadState(LoadState.DOMCONTENTLOADED);
         System.out.println(popup.title()); // Popup is ready to use.
         
        Specified by:
        waitForLoadState in interface Page
        Parameters:
        state - Optional load state to wait for, defaults to load. If the state has been already reached while loading current document, the method resolves immediately. Can be one of:
        • "load" - wait for the load event to be fired.
        • "domcontentloaded" - wait for the DOMContentLoaded event to be fired.
        • "networkidle" - **DISCOURAGED** wait until there are no network connections for at least 500 ms. Don't use this method for testing, rely on web assertions to assess readiness instead.
      • frameNavigated

        void frameNavigated​(FrameImpl frame)
      • createWaitableFrameDetach

        <T> Waitable<T> createWaitableFrameDetach​(Frame frame)
      • createWaitForCloseHelper

        <T> Waitable<T> createWaitForCloseHelper()
      • waitForRequest

        public Request waitForRequest​(java.lang.String urlGlob,
                                      Page.WaitForRequestOptions options,
                                      java.lang.Runnable code)
        Description copied from interface: Page
        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();
         });
         
        Specified by:
        waitForRequest in interface Page
        Parameters:
        urlGlob - Request URL string, regex or predicate receiving Request object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        code - Callback that performs the action triggering the event.
      • waitForRequest

        public Request waitForRequest​(java.util.regex.Pattern urlPattern,
                                      Page.WaitForRequestOptions options,
                                      java.lang.Runnable code)
        Description copied from interface: Page
        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();
         });
         
        Specified by:
        waitForRequest in interface Page
        Parameters:
        urlPattern - Request URL string, regex or predicate receiving Request object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        code - Callback that performs the action triggering the event.
      • waitForRequest

        public Request waitForRequest​(java.util.function.Predicate<Request> predicate,
                                      Page.WaitForRequestOptions options,
                                      java.lang.Runnable code)
        Description copied from interface: Page
        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();
         });
         
        Specified by:
        waitForRequest in interface Page
        Parameters:
        predicate - Request URL string, regex or predicate receiving Request object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        code - Callback that performs the action triggering the event.
      • waitForRequestFinished

        public Request waitForRequestFinished​(Page.WaitForRequestFinishedOptions options,
                                              java.lang.Runnable code)
        Description copied from interface: Page
        Performs action and waits for a Request to finish loading. If predicate is provided, it passes Request value into the predicate function and waits for predicate(request) to return a truthy value. Will throw an error if the page is closed before the Page.onRequestFinished() event is fired.
        Specified by:
        waitForRequestFinished in interface Page
        code - Callback that performs the action triggering the event.
      • waitForResponse

        public Response waitForResponse​(java.lang.String urlGlob,
                                        Page.WaitForResponseOptions options,
                                        java.lang.Runnable code)
        Description copied from interface: Page
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Specified by:
        waitForResponse in interface Page
        Parameters:
        urlGlob - Request URL string, regex or predicate receiving Response object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        code - Callback that performs the action triggering the event.
      • waitForResponse

        public Response waitForResponse​(java.util.regex.Pattern urlPattern,
                                        Page.WaitForResponseOptions options,
                                        java.lang.Runnable code)
        Description copied from interface: Page
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Specified by:
        waitForResponse in interface Page
        Parameters:
        urlPattern - Request URL string, regex or predicate receiving Response object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        code - Callback that performs the action triggering the event.
      • waitForResponse

        public Response waitForResponse​(java.util.function.Predicate<Response> predicate,
                                        Page.WaitForResponseOptions options,
                                        java.lang.Runnable code)
        Description copied from interface: Page
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Specified by:
        waitForResponse in interface Page
        Parameters:
        predicate - Request URL string, regex or predicate receiving Response object. When a baseURL via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor.
        code - Callback that performs the action triggering the event.
      • waitForSelector

        public ElementHandle waitForSelector​(java.lang.String selector,
                                             Page.WaitForSelectorOptions options)
        Description copied from interface: Page
        Returns when element specified by selector satisfies state option. Returns null if waiting for hidden or detached.

        NOTE: Playwright automatically waits for element to be ready before performing an action. Using Locator objects and web-first assertions makes the code wait-for-selector-free.

        Wait for the selector to satisfy state option (either appear/disappear from dom, or become visible/hidden). If at the moment of calling the method selector already satisfies the condition, the method will return immediately. If the selector doesn't satisfy the condition for the timeout milliseconds, the function will throw.

        **Usage**

        This method works across navigations:

        
         import com.microsoft.playwright.*;
        
         public class Example {
           public static void main(String[] args) {
             try (Playwright playwright = Playwright.create()) {
               BrowserType chromium = playwright.chromium();
               Browser browser = chromium.launch();
               Page page = browser.newPage();
               for (String currentURL : Arrays.asList("https://google.com", "https://bbc.com")) {
                 page.navigate(currentURL);
                 ElementHandle element = page.waitForSelector("img");
                 System.out.println("Loaded image: " + element.getAttribute("src"));
               }
               browser.close();
             }
           }
         }
         
        Specified by:
        waitForSelector in interface Page
        Parameters:
        selector - A selector to query for.
      • waitForCondition

        public void waitForCondition​(java.util.function.BooleanSupplier predicate,
                                     Page.WaitForConditionOptions options)
        Description copied from interface: Page
        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);
         
        Specified by:
        waitForCondition in interface Page
        Parameters:
        predicate - Condition to wait for.
      • waitForTimeout

        public void waitForTimeout​(double timeout)
        Description copied from interface: Page
        Waits for the given timeout in milliseconds.

        Note that page.waitForTimeout() should only be used for debugging. Tests using the timer in production are going to be flaky. Use signals such as network events, selectors becoming visible and others instead.

        **Usage**

        
         // wait for 1 second
         page.waitForTimeout(1000);
         
        Specified by:
        waitForTimeout in interface Page
        Parameters:
        timeout - A timeout to wait for
      • waitForURL

        public void waitForURL​(java.lang.String url,
                               Page.WaitForURLOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        waitForURL in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
      • waitForURL

        public void waitForURL​(java.util.regex.Pattern url,
                               Page.WaitForURLOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        waitForURL in interface Page
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
      • waitForURL

        public void waitForURL​(java.util.function.Predicate<java.lang.String> url,
                               Page.WaitForURLOptions options)
        Description copied from interface: Page
        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");
         
        Specified by:
        waitForURL in interface Page
        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.
      • workers

        public java.util.List<Worker> workers()
        Description copied from interface: Page
        This method returns all of the dedicated WebWorkers associated with the page.

        NOTE: This does not contain ServiceWorkers

        Specified by:
        workers in interface Page
      • onceDialog

        public void onceDialog​(java.util.function.Consumer<Dialog> handler)
        Description copied from interface: Page
        Adds one-off Dialog handler. The handler will be removed immediately after next Dialog is created.
        
         page.onceDialog(dialog -> {
           dialog.accept("foo");
         });
        
         // prints 'foo'
         System.out.println(page.evaluate("prompt('Enter string:')"));
        
         // prints 'null' as the dialog will be auto-dismissed because there are no handlers.
         System.out.println(page.evaluate("prompt('Enter string:')"));
         

        This code above is equivalent to:

        {@code
         Consumer handler = new Consumer() {
        Specified by:
        onceDialog in interface Page
        Parameters:
        handler - Receives the Dialog object, it **must** either Dialog.accept() or Dialog.dismiss() the dialog - otherwise the page will freeze waiting for the dialog, and actions like click will never finish.