Interface Page

  • All Superinterfaces:
    java.lang.AutoCloseable
    All Known Implementing Classes:
    PageImpl

    public interface Page
    extends java.lang.AutoCloseable
    Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium. One Browser instance might have multiple Page instances.

    This example creates a page, navigates it to a URL, and then saves a screenshot:

    
     import com.microsoft.playwright.*;
    
     public class Example {
       public static void main(String[] args) {
         try (Playwright playwright = Playwright.create()) {
           BrowserType webkit = playwright.webkit();
           Browser browser = webkit.launch();
           BrowserContext context = browser.newContext();
           Page page = context.newPage();
           page.navigate("https://example.com");
           page.screenshot(new Page.ScreenshotOptions().setPath(Paths.get("screenshot.png")));
           browser.close();
         }
       }
     }
     

    The Page class emits various events (described below) which can be handled using any of Node's native EventEmitter methods, such as on, once or removeListener.

    This example logs a message for a single page load event:

    
     page.onLoad(p -> System.out.println("Page loaded!"));
     

    To unsubscribe from events use the removeListener method:

    
     Consumer<Request> logRequest = interceptedRequest -> {
       System.out.println("A request was made: " + interceptedRequest.url());
     };
     page.onRequest(logRequest);
     // Sometime later...
     page.offRequest(logRequest);
     
    • Method Detail

      • onClose

        void onClose​(java.util.function.Consumer<Page> handler)
        Emitted when the page closes.
      • offClose

        void offClose​(java.util.function.Consumer<Page> handler)
        Removes handler that was previously added with onClose(handler).
      • onConsoleMessage

        void onConsoleMessage​(java.util.function.Consumer<ConsoleMessage> handler)
        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' })");
         
      • onCrash

        void onCrash​(java.util.function.Consumer<Page> handler)
        Emitted when the page crashes. Browser pages might crash if they try to allocate too much memory. When the page crashes, ongoing and subsequent operations will throw.

        The most common way to deal with crashes is to catch an exception:

        
         try {
           // Crash might happen during a click.
           page.click("button");
           // Or while waiting for an event.
           page.waitForPopup(() -> {});
         } catch (PlaywrightException e) {
           // When the page crashes, exception message contains "crash".
         }
         
      • offCrash

        void offCrash​(java.util.function.Consumer<Page> handler)
        Removes handler that was previously added with onCrash(handler).
      • onDialog

        void onDialog​(java.util.function.Consumer<Dialog> handler)
        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.

      • offDialog

        void offDialog​(java.util.function.Consumer<Dialog> handler)
        Removes handler that was previously added with onDialog(handler).
      • onDOMContentLoaded

        void onDOMContentLoaded​(java.util.function.Consumer<Page> handler)
        Emitted when the JavaScript DOMContentLoaded event is dispatched.
      • offDOMContentLoaded

        void offDOMContentLoaded​(java.util.function.Consumer<Page> handler)
        Removes handler that was previously added with onDOMContentLoaded(handler).
      • onDownload

        void onDownload​(java.util.function.Consumer<Download> handler)
        Emitted when attachment download started. User can access basic file operations on downloaded content via the passed Download instance.
      • offDownload

        void offDownload​(java.util.function.Consumer<Download> handler)
        Removes handler that was previously added with onDownload(handler).
      • onFileChooser

        void onFileChooser​(java.util.function.Consumer<FileChooser> handler)
        Emitted when a file chooser is supposed to appear, such as after clicking the <input type=file>. Playwright can respond to it via setting the input files using FileChooser.setFiles() that can be uploaded after that.
        
         page.onFileChooser(fileChooser -> {
           fileChooser.setFiles(Paths.get("/tmp/myfile.pdf"));
         });
         
      • onFrameAttached

        void onFrameAttached​(java.util.function.Consumer<Frame> handler)
        Emitted when a frame is attached.
      • offFrameAttached

        void offFrameAttached​(java.util.function.Consumer<Frame> handler)
        Removes handler that was previously added with onFrameAttached(handler).
      • onFrameDetached

        void onFrameDetached​(java.util.function.Consumer<Frame> handler)
        Emitted when a frame is detached.
      • offFrameDetached

        void offFrameDetached​(java.util.function.Consumer<Frame> handler)
        Removes handler that was previously added with onFrameDetached(handler).
      • onFrameNavigated

        void onFrameNavigated​(java.util.function.Consumer<Frame> handler)
        Emitted when a frame is navigated to a new url.
      • offFrameNavigated

        void offFrameNavigated​(java.util.function.Consumer<Frame> handler)
        Removes handler that was previously added with onFrameNavigated(handler).
      • onLoad

        void onLoad​(java.util.function.Consumer<Page> handler)
        Emitted when the JavaScript load event is dispatched.
      • offLoad

        void offLoad​(java.util.function.Consumer<Page> handler)
        Removes handler that was previously added with onLoad(handler).
      • onPageError

        void onPageError​(java.util.function.Consumer<java.lang.String> handler)
        Emitted when an uncaught exception happens within the page.
        
         // Log all uncaught errors to the terminal
         page.onPageError(exception -> {
           System.out.println("Uncaught exception: " + exception);
         });
        
         // Navigate to a page with an exception.
         page.navigate("data:text/html,<script>throw new Error('Test')</script>");
         
      • offPageError

        void offPageError​(java.util.function.Consumer<java.lang.String> handler)
        Removes handler that was previously added with onPageError(handler).
      • onPopup

        void onPopup​(java.util.function.Consumer<Page> handler)
        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).

      • offPopup

        void offPopup​(java.util.function.Consumer<Page> handler)
        Removes handler that was previously added with onPopup(handler).
      • onRequest

        void onRequest​(java.util.function.Consumer<Request> handler)
        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().
      • offRequest

        void offRequest​(java.util.function.Consumer<Request> handler)
        Removes handler that was previously added with onRequest(handler).
      • onRequestFailed

        void onRequestFailed​(java.util.function.Consumer<Request> handler)
        Emitted when a request fails, for example by timing out.
        
         page.onRequestFailed(request -> {
           System.out.println(request.url() + " " + request.failure());
         });
         

        NOTE: HTTP Error responses, such as 404 or 503, are still successful responses from HTTP standpoint, so request will complete with Page.onRequestFinished() event and not 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.

      • offRequestFailed

        void offRequestFailed​(java.util.function.Consumer<Request> handler)
        Removes handler that was previously added with onRequestFailed(handler).
      • onRequestFinished

        void onRequestFinished​(java.util.function.Consumer<Request> handler)
        Emitted when a request finishes successfully after downloading the response body. For a successful response, the sequence of events is request, response and requestfinished.
      • offRequestFinished

        void offRequestFinished​(java.util.function.Consumer<Request> handler)
        Removes handler that was previously added with onRequestFinished(handler).
      • onResponse

        void onResponse​(java.util.function.Consumer<Response> handler)
        Emitted when [response] status and headers are received for a request. For a successful response, the sequence of events is request, response and requestfinished.
      • offResponse

        void offResponse​(java.util.function.Consumer<Response> handler)
        Removes handler that was previously added with onResponse(handler).
      • onWebSocket

        void onWebSocket​(java.util.function.Consumer<WebSocket> handler)
        Emitted when WebSocket request is sent.
      • offWebSocket

        void offWebSocket​(java.util.function.Consumer<WebSocket> handler)
        Removes handler that was previously added with onWebSocket(handler).
      • onWorker

        void onWorker​(java.util.function.Consumer<Worker> handler)
        Emitted when a dedicated WebWorker is spawned by the page.
      • offWorker

        void offWorker​(java.util.function.Consumer<Worker> handler)
        Removes handler that was previously added with onWorker(handler).
      • addInitScript

        void addInitScript​(java.lang.String script)
        Adds a script which would be evaluated in one of the following scenarios:
        • Whenever the page is navigated.
        • Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.

        The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

        **Usage**

        An example of overriding Math.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.

        Parameters:
        script - Script to be evaluated in all pages in the browser context.
        Since:
        v1.8
      • addInitScript

        void addInitScript​(java.nio.file.Path script)
        Adds a script which would be evaluated in one of the following scenarios:
        • Whenever the page is navigated.
        • Whenever the child frame is attached or navigated. In this case, the script is evaluated in the context of the newly attached frame.

        The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.

        **Usage**

        An example of overriding Math.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.

        Parameters:
        script - Script to be evaluated in all pages in the browser context.
        Since:
        v1.8
      • addScriptTag

        default ElementHandle addScriptTag()
        Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.
        Since:
        v1.8
      • addScriptTag

        ElementHandle addScriptTag​(Page.AddScriptTagOptions options)
        Adds a <script> tag into the page with the desired url or content. Returns the added tag when the script's onload fires or when the script content was injected into frame.
        Since:
        v1.8
      • addStyleTag

        default ElementHandle addStyleTag()
        Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
        Since:
        v1.8
      • addStyleTag

        ElementHandle addStyleTag​(Page.AddStyleTagOptions options)
        Adds a <link rel="stylesheet"> tag into the page with the desired url or a <style type="text/css"> tag with the content. Returns the added tag when the stylesheet's onload fires or when the CSS content was injected into frame.
        Since:
        v1.8
      • bringToFront

        void bringToFront()
        Brings page to front (activates tab).
        Since:
        v1.8
      • check

        default void check​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • check

        void check​(java.lang.String selector,
                   Page.CheckOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • click

        default void click​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • click

        void click​(java.lang.String selector,
                   Page.ClickOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • close

        default void close()
        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 java.lang.AutoCloseable
        Since:
        v1.8
      • close

        void close​(Page.CloseOptions options)
        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.

        Since:
        v1.8
      • content

        java.lang.String content()
        Gets the full HTML contents of the page, including the doctype.
        Since:
        v1.8
      • context

        BrowserContext context()
        Get the browser context that the page belongs to.
        Since:
        v1.8
      • dblclick

        default void dblclick​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • dblclick

        void dblclick​(java.lang.String selector,
                      Page.DblclickOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • dispatchEvent

        default void dispatchEvent​(java.lang.String selector,
                                   java.lang.String type,
                                   java.lang.Object eventInit)
        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);
         
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        type - DOM event type: "click", "dragstart", etc.
        eventInit - Optional event-specific initialization properties.
        Since:
        v1.8
      • dispatchEvent

        default void dispatchEvent​(java.lang.String selector,
                                   java.lang.String type)
        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);
         
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        type - DOM event type: "click", "dragstart", etc.
        Since:
        v1.8
      • dispatchEvent

        void dispatchEvent​(java.lang.String selector,
                           java.lang.String type,
                           java.lang.Object eventInit,
                           Page.DispatchEventOptions options)
        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);
         
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        type - DOM event type: "click", "dragstart", etc.
        eventInit - Optional event-specific initialization properties.
        Since:
        v1.8
      • dragAndDrop

        default void dragAndDrop​(java.lang.String source,
                                 java.lang.String target)
        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));
         
        Parameters:
        source - A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
        target - A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.13
      • dragAndDrop

        void dragAndDrop​(java.lang.String source,
                         java.lang.String target,
                         Page.DragAndDropOptions options)
        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));
         
        Parameters:
        source - A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used.
        target - A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.13
      • emulateMedia

        default void emulateMedia()
        This method changes 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
         
        Since:
        v1.8
      • emulateMedia

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

        **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
         
        Since:
        v1.8
      • evalOnSelector

        default java.lang.Object evalOnSelector​(java.lang.String selector,
                                                java.lang.String expression,
                                                java.lang.Object arg)
        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");
         
        Parameters:
        selector - A selector to query for.
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
        Since:
        v1.9
      • evalOnSelector

        default java.lang.Object evalOnSelector​(java.lang.String selector,
                                                java.lang.String expression)
        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");
         
        Parameters:
        selector - A selector to query for.
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        Since:
        v1.9
      • evalOnSelector

        java.lang.Object evalOnSelector​(java.lang.String selector,
                                        java.lang.String expression,
                                        java.lang.Object arg,
                                        Page.EvalOnSelectorOptions options)
        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");
         
        Parameters:
        selector - A selector to query for.
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
        Since:
        v1.9
      • evalOnSelectorAll

        default java.lang.Object evalOnSelectorAll​(java.lang.String selector,
                                                   java.lang.String expression)
        The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to expression. 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);
         
        Parameters:
        selector - A selector to query for.
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        Since:
        v1.9
      • evalOnSelectorAll

        java.lang.Object evalOnSelectorAll​(java.lang.String selector,
                                           java.lang.String expression,
                                           java.lang.Object arg)
        The method finds all elements matching the specified selector within the page and passes an array of matched elements as a first argument to expression. 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);
         
        Parameters:
        selector - A selector to query for.
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        arg - Optional argument to pass to expression.
        Since:
        v1.9
      • evaluate

        default java.lang.Object evaluate​(java.lang.String expression)
        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();
         
        Parameters:
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        Since:
        v1.8
      • evaluate

        java.lang.Object evaluate​(java.lang.String expression,
                                  java.lang.Object arg)
        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();
         
        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.
        Since:
        v1.8
      • evaluateHandle

        default JSHandle evaluateHandle​(java.lang.String expression)
        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();
         
        Parameters:
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        Since:
        v1.8
      • evaluateHandle

        JSHandle evaluateHandle​(java.lang.String expression,
                                java.lang.Object arg)
        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();
         
        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.
        Since:
        v1.8
      • exposeBinding

        default void exposeBinding​(java.lang.String name,
                                   BindingCallback callback)
        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");
         
        Parameters:
        name - Name of the function on the window object.
        callback - Callback function that will be called in the Playwright's context.
        Since:
        v1.8
      • exposeBinding

        void exposeBinding​(java.lang.String name,
                           BindingCallback callback,
                           Page.ExposeBindingOptions options)
        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");
         
        Parameters:
        name - Name of the function on the window object.
        callback - Callback function that will be called in the Playwright's context.
        Since:
        v1.8
      • exposeFunction

        void exposeFunction​(java.lang.String name,
                            FunctionCallback callback)
        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");
             }
           }
         }
         
        Parameters:
        name - Name of the function on the window object
        callback - Callback function which will be called in Playwright's context.
        Since:
        v1.8
      • fill

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

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

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

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        value - Value to fill for the <input>, <textarea> or [contenteditable] element.
        Since:
        v1.8
      • fill

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

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

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

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        value - Value to fill for the <input>, <textarea> or [contenteditable] element.
        Since:
        v1.8
      • focus

        default void focus​(java.lang.String selector)
        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.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • focus

        void focus​(java.lang.String selector,
                   Page.FocusOptions options)
        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.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • frame

        Frame frame​(java.lang.String name)
        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.*");
         
        Parameters:
        name - Frame name specified in the iframe's name attribute.
        Since:
        v1.8
      • frameByUrl

        Frame frameByUrl​(java.lang.String url)
        Returns frame with matching URL.
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.
        Since:
        v1.9
      • frameByUrl

        Frame frameByUrl​(java.util.regex.Pattern url)
        Returns frame with matching URL.
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.
        Since:
        v1.9
      • frameByUrl

        Frame frameByUrl​(java.util.function.Predicate<java.lang.String> url)
        Returns frame with matching URL.
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving frame's url as a [URL] object.
        Since:
        v1.9
      • frameLocator

        FrameLocator frameLocator​(java.lang.String selector)
        When working with iframes, you can create a frame locator that will enter the iframe and allow selecting elements in that iframe.

        **Usage**

        Following snippet locates element with text "Submit" in the iframe with id my-frame, like <iframe id="my-frame">:

        
         Locator locator = page.frameLocator("#my-iframe").getByText("Submit");
         locator.click();
         
        Parameters:
        selector - A selector to use when resolving DOM element.
        Since:
        v1.17
      • frames

        java.util.List<Frame> frames()
        An array of all frames attached to the page.
        Since:
        v1.8
      • getAttribute

        default java.lang.String getAttribute​(java.lang.String selector,
                                              java.lang.String name)
        Returns element attribute value.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        name - Attribute name to get the value for.
        Since:
        v1.8
      • getAttribute

        java.lang.String getAttribute​(java.lang.String selector,
                                      java.lang.String name,
                                      Page.GetAttributeOptions options)
        Returns element attribute value.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        name - Attribute name to get the value for.
        Since:
        v1.8
      • getByAltText

        default Locator getByAltText​(java.lang.String text)
        Allows locating elements by their alt text.

        **Usage**

        For example, this method will find the image by alt text "Playwright logo":

        
         page.getByAltText("Playwright logo").click();
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByAltText

        Locator getByAltText​(java.lang.String text,
                             Page.GetByAltTextOptions options)
        Allows locating elements by their alt text.

        **Usage**

        For example, this method will find the image by alt text "Playwright logo":

        
         page.getByAltText("Playwright logo").click();
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByAltText

        default Locator getByAltText​(java.util.regex.Pattern text)
        Allows locating elements by their alt text.

        **Usage**

        For example, this method will find the image by alt text "Playwright logo":

        
         page.getByAltText("Playwright logo").click();
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByAltText

        Locator getByAltText​(java.util.regex.Pattern text,
                             Page.GetByAltTextOptions options)
        Allows locating elements by their alt text.

        **Usage**

        For example, this method will find the image by alt text "Playwright logo":

        
         page.getByAltText("Playwright logo").click();
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByLabel

        default Locator getByLabel​(java.lang.String text)
        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");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByLabel

        Locator getByLabel​(java.lang.String text,
                           Page.GetByLabelOptions options)
        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");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByLabel

        default Locator getByLabel​(java.util.regex.Pattern text)
        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");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByLabel

        Locator getByLabel​(java.util.regex.Pattern text,
                           Page.GetByLabelOptions options)
        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");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByPlaceholder

        default Locator getByPlaceholder​(java.lang.String text)
        Allows locating input elements by the placeholder text.

        **Usage**

        For example, consider the following DOM structure.

        You can fill the input after locating it by the placeholder text:

        
         page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByPlaceholder

        Locator getByPlaceholder​(java.lang.String text,
                                 Page.GetByPlaceholderOptions options)
        Allows locating input elements by the placeholder text.

        **Usage**

        For example, consider the following DOM structure.

        You can fill the input after locating it by the placeholder text:

        
         page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByPlaceholder

        default Locator getByPlaceholder​(java.util.regex.Pattern text)
        Allows locating input elements by the placeholder text.

        **Usage**

        For example, consider the following DOM structure.

        You can fill the input after locating it by the placeholder text:

        
         page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByPlaceholder

        Locator getByPlaceholder​(java.util.regex.Pattern text,
                                 Page.GetByPlaceholderOptions options)
        Allows locating input elements by the placeholder text.

        **Usage**

        For example, consider the following DOM structure.

        You can fill the input after locating it by the placeholder text:

        
         page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByRole

        default Locator getByRole​(AriaRole role)
        Allows locating elements by their ARIA role, ARIA attributes and accessible name.

        **Usage**

        Consider the following DOM structure.

        You can locate each element by it's implicit role:

        
         assertThat(page
             .getByRole(AriaRole.HEADING,
                        new Page.GetByRoleOptions().setName("Sign up")))
             .isVisible();
        
         page.getByRole(AriaRole.CHECKBOX,
                        new Page.GetByRoleOptions().setName("Subscribe"))
             .check();
        
         page.getByRole(AriaRole.BUTTON,
                        new Page.GetByRoleOptions().setName(
                            Pattern.compile("submit", Pattern.CASE_INSENSITIVE)))
             .click();
         

        **Details**

        Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

        Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.

        Parameters:
        role - Required aria role.
        Since:
        v1.27
      • getByRole

        Locator getByRole​(AriaRole role,
                          Page.GetByRoleOptions options)
        Allows locating elements by their ARIA role, ARIA attributes and accessible name.

        **Usage**

        Consider the following DOM structure.

        You can locate each element by it's implicit role:

        
         assertThat(page
             .getByRole(AriaRole.HEADING,
                        new Page.GetByRoleOptions().setName("Sign up")))
             .isVisible();
        
         page.getByRole(AriaRole.CHECKBOX,
                        new Page.GetByRoleOptions().setName("Subscribe"))
             .check();
        
         page.getByRole(AriaRole.BUTTON,
                        new Page.GetByRoleOptions().setName(
                            Pattern.compile("submit", Pattern.CASE_INSENSITIVE)))
             .click();
         

        **Details**

        Role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines.

        Many html elements have an implicitly defined role that is recognized by the role selector. You can find all the supported roles here. ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting role and/or aria-* attributes to default values.

        Parameters:
        role - Required aria role.
        Since:
        v1.27
      • getByTestId

        Locator getByTestId​(java.lang.String testId)
        Locate element by the test id.

        **Usage**

        Consider the following DOM structure.

        You can locate the element by it's test id:

        
         page.getByTestId("directions").click();
         

        **Details**

        By default, the data-testid attribute is used as a test id. Use Selectors.setTestIdAttribute() to configure a different test id attribute if necessary.

        Parameters:
        testId - Id to locate the element by.
        Since:
        v1.27
      • getByTestId

        Locator getByTestId​(java.util.regex.Pattern testId)
        Locate element by the test id.

        **Usage**

        Consider the following DOM structure.

        You can locate the element by it's test id:

        
         page.getByTestId("directions").click();
         

        **Details**

        By default, the data-testid attribute is used as a test id. Use Selectors.setTestIdAttribute() to configure a different test id attribute if necessary.

        Parameters:
        testId - Id to locate the element by.
        Since:
        v1.27
      • getByText

        default Locator getByText​(java.lang.String text)
        Allows locating elements that contain given text.

        See also Locator.filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.

        **Usage**

        Consider the following DOM structure:

        You can locate by text substring, exact string, or a regular expression:

        
         // Matches <span>
         page.getByText("world")
        
         // Matches first <div>
         page.getByText("Hello world")
        
         // Matches second <div>
         page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
        
         // Matches both <div>s
         page.getByText(Pattern.compile("Hello"))
        
         // Matches second <div>
         page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
         

        **Details**

        Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

        Input elements of the type 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">.

        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByText

        Locator getByText​(java.lang.String text,
                          Page.GetByTextOptions options)
        Allows locating elements that contain given text.

        See also Locator.filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.

        **Usage**

        Consider the following DOM structure:

        You can locate by text substring, exact string, or a regular expression:

        
         // Matches <span>
         page.getByText("world")
        
         // Matches first <div>
         page.getByText("Hello world")
        
         // Matches second <div>
         page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
        
         // Matches both <div>s
         page.getByText(Pattern.compile("Hello"))
        
         // Matches second <div>
         page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
         

        **Details**

        Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

        Input elements of the type 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">.

        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByText

        default Locator getByText​(java.util.regex.Pattern text)
        Allows locating elements that contain given text.

        See also Locator.filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.

        **Usage**

        Consider the following DOM structure:

        You can locate by text substring, exact string, or a regular expression:

        
         // Matches <span>
         page.getByText("world")
        
         // Matches first <div>
         page.getByText("Hello world")
        
         // Matches second <div>
         page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
        
         // Matches both <div>s
         page.getByText(Pattern.compile("Hello"))
        
         // Matches second <div>
         page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
         

        **Details**

        Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

        Input elements of the type 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">.

        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByText

        Locator getByText​(java.util.regex.Pattern text,
                          Page.GetByTextOptions options)
        Allows locating elements that contain given text.

        See also Locator.filter() that allows to match by another criteria, like an accessible role, and then filter by the text content.

        **Usage**

        Consider the following DOM structure:

        You can locate by text substring, exact string, or a regular expression:

        
         // Matches <span>
         page.getByText("world")
        
         // Matches first <div>
         page.getByText("Hello world")
        
         // Matches second <div>
         page.getByText("Hello", new Page.GetByTextOptions().setExact(true))
        
         // Matches both <div>s
         page.getByText(Pattern.compile("Hello"))
        
         // Matches second <div>
         page.getByText(Pattern.compile("^hello$", Pattern.CASE_INSENSITIVE))
         

        **Details**

        Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.

        Input elements of the type 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">.

        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByTitle

        default Locator getByTitle​(java.lang.String text)
        Allows locating elements by their title attribute.

        **Usage**

        Consider the following DOM structure.

        You can check the issues count after locating it by the title text:

        
         assertThat(page.getByTitle("Issues count")).hasText("25 issues");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByTitle

        Locator getByTitle​(java.lang.String text,
                           Page.GetByTitleOptions options)
        Allows locating elements by their title attribute.

        **Usage**

        Consider the following DOM structure.

        You can check the issues count after locating it by the title text:

        
         assertThat(page.getByTitle("Issues count")).hasText("25 issues");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByTitle

        default Locator getByTitle​(java.util.regex.Pattern text)
        Allows locating elements by their title attribute.

        **Usage**

        Consider the following DOM structure.

        You can check the issues count after locating it by the title text:

        
         assertThat(page.getByTitle("Issues count")).hasText("25 issues");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • getByTitle

        Locator getByTitle​(java.util.regex.Pattern text,
                           Page.GetByTitleOptions options)
        Allows locating elements by their title attribute.

        **Usage**

        Consider the following DOM structure.

        You can check the issues count after locating it by the title text:

        
         assertThat(page.getByTitle("Issues count")).hasText("25 issues");
         
        Parameters:
        text - Text to locate the element for.
        Since:
        v1.27
      • goBack

        default Response goBack()
        Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns null.

        Navigate to the previous page in history.

        Since:
        v1.8
      • goBack

        Response goBack​(Page.GoBackOptions options)
        Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go back, returns null.

        Navigate to the previous page in history.

        Since:
        v1.8
      • goForward

        default Response goForward()
        Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns null.

        Navigate to the next page in history.

        Since:
        v1.8
      • goForward

        Response goForward​(Page.GoForwardOptions options)
        Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect. If can not go forward, returns null.

        Navigate to the next page in history.

        Since:
        v1.8
      • navigate

        default Response navigate​(java.lang.String url)
        Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.

        The method will throw an error if:

        • there's an SSL error (e.g. in case of self-signed certificates).
        • target URL is invalid.
        • the 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.

        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.
        Since:
        v1.8
      • navigate

        Response navigate​(java.lang.String url,
                          Page.NavigateOptions options)
        Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.

        The method will throw an error if:

        • there's an SSL error (e.g. in case of self-signed certificates).
        • target URL is invalid.
        • the 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.

        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.
        Since:
        v1.8
      • hover

        default void hover​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • hover

        void hover​(java.lang.String selector,
                   Page.HoverOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • innerHTML

        default java.lang.String innerHTML​(java.lang.String selector)
        Returns element.innerHTML.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • innerHTML

        java.lang.String innerHTML​(java.lang.String selector,
                                   Page.InnerHTMLOptions options)
        Returns element.innerHTML.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • innerText

        default java.lang.String innerText​(java.lang.String selector)
        Returns element.innerText.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • innerText

        java.lang.String innerText​(java.lang.String selector,
                                   Page.InnerTextOptions options)
        Returns element.innerText.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • inputValue

        default java.lang.String inputValue​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.13
      • inputValue

        java.lang.String inputValue​(java.lang.String selector,
                                    Page.InputValueOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.13
      • isChecked

        default boolean isChecked​(java.lang.String selector)
        Returns whether the element is checked. Throws if the element is not a checkbox or radio input.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isChecked

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

        boolean isClosed()
        Indicates that the page has been closed.
        Since:
        v1.8
      • isDisabled

        default boolean isDisabled​(java.lang.String selector)
        Returns whether the element is disabled, the opposite of enabled.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isDisabled

        boolean isDisabled​(java.lang.String selector,
                           Page.IsDisabledOptions options)
        Returns whether the element is disabled, the opposite of enabled.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isEditable

        default boolean isEditable​(java.lang.String selector)
        Returns whether the element is editable.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isEditable

        boolean isEditable​(java.lang.String selector,
                           Page.IsEditableOptions options)
        Returns whether the element is editable.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isEnabled

        default boolean isEnabled​(java.lang.String selector)
        Returns whether the element is enabled.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isEnabled

        boolean isEnabled​(java.lang.String selector,
                          Page.IsEnabledOptions options)
        Returns whether the element is enabled.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isHidden

        default boolean isHidden​(java.lang.String selector)
        Returns whether the element is hidden, the opposite of visible. selector that does not match any elements is considered hidden.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isHidden

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

        default boolean isVisible​(java.lang.String selector)
        Returns whether the element is visible. selector that does not match any elements is considered not visible.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • isVisible

        boolean isVisible​(java.lang.String selector,
                          Page.IsVisibleOptions options)
        Returns whether the element is visible. selector that does not match any elements is considered not visible.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • keyboard

        Keyboard keyboard()
        Since:
        v1.8
      • locator

        default Locator locator​(java.lang.String selector)
        The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.

        Learn more about locators.

        Parameters:
        selector - A selector to use when resolving DOM element.
        Since:
        v1.14
      • locator

        Locator locator​(java.lang.String selector,
                        Page.LocatorOptions options)
        The method returns an element locator that can be used to perform actions on this page / frame. Locator is resolved to the element immediately before performing an action, so a series of actions on the same locator can in fact be performed on different DOM elements. That would happen if the DOM structure between those actions has changed.

        Learn more about locators.

        Parameters:
        selector - A selector to use when resolving DOM element.
        Since:
        v1.14
      • mainFrame

        Frame mainFrame()
        The page's main frame. Page is guaranteed to have a main frame which persists during navigations.
        Since:
        v1.8
      • mouse

        Mouse mouse()
        Since:
        v1.8
      • onceDialog

        void onceDialog​(java.util.function.Consumer<Dialog> handler)
        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() {
        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.
        Since:
        v1.10
      • opener

        Page opener()
        Returns the opener for popup pages and null for others. If the opener has been closed already the returns null.
        Since:
        v1.8
      • pause

        void pause()
        Pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or to 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().

        Since:
        v1.9
      • pdf

        default byte[] pdf()
        Returns the PDF buffer.

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

        page.pdf() generates a pdf of the page 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.

        Since:
        v1.8
      • pdf

        byte[] pdf​(Page.PdfOptions options)
        Returns the PDF buffer.

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

        page.pdf() generates a pdf of the page 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.

        Since:
        v1.8
      • press

        default void press​(java.lang.String selector,
                           java.lang.String key)
        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" )));
         
        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.
        Since:
        v1.8
      • press

        void press​(java.lang.String selector,
                   java.lang.String key,
                   Page.PressOptions options)
        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" )));
         
        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.
        Since:
        v1.8
      • querySelector

        default ElementHandle querySelector​(java.lang.String selector)
        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().
        Parameters:
        selector - A selector to query for.
        Since:
        v1.9
      • querySelector

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

        java.util.List<ElementHandle> querySelectorAll​(java.lang.String selector)
        The method finds all elements matching the specified selector within the page. If no elements match the selector, the return value resolves to [].
        Parameters:
        selector - A selector to query for.
        Since:
        v1.9
      • reload

        default Response reload()
        This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
        Since:
        v1.8
      • reload

        Response reload​(Page.ReloadOptions options)
        This method reloads the current page, in the same way as if the user had triggered a browser refresh. Returns the main resource response. In case of multiple redirects, the navigation will resolve with the response of the last redirect.
        Since:
        v1.8
      • route

        default void route​(java.lang.String url,
                           java.util.function.Consumer<Route> handler)
        Routing provides the capability to modify network requests that are made by a page.

        Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

        NOTE: The handler will only be called for the first url if the response is a redirect.

        NOTE: Page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by 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.

        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.
        Since:
        v1.8
      • route

        void route​(java.lang.String url,
                   java.util.function.Consumer<Route> handler,
                   Page.RouteOptions options)
        Routing provides the capability to modify network requests that are made by a page.

        Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

        NOTE: The handler will only be called for the first url if the response is a redirect.

        NOTE: Page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by 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.

        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.
        Since:
        v1.8
      • route

        default void route​(java.util.regex.Pattern url,
                           java.util.function.Consumer<Route> handler)
        Routing provides the capability to modify network requests that are made by a page.

        Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

        NOTE: The handler will only be called for the first url if the response is a redirect.

        NOTE: Page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by 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.

        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.
        Since:
        v1.8
      • route

        void route​(java.util.regex.Pattern url,
                   java.util.function.Consumer<Route> handler,
                   Page.RouteOptions options)
        Routing provides the capability to modify network requests that are made by a page.

        Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

        NOTE: The handler will only be called for the first url if the response is a redirect.

        NOTE: Page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by 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.

        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.
        Since:
        v1.8
      • route

        default void route​(java.util.function.Predicate<java.lang.String> url,
                           java.util.function.Consumer<Route> handler)
        Routing provides the capability to modify network requests that are made by a page.

        Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

        NOTE: The handler will only be called for the first url if the response is a redirect.

        NOTE: Page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by 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.

        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.
        Since:
        v1.8
      • route

        void route​(java.util.function.Predicate<java.lang.String> url,
                   java.util.function.Consumer<Route> handler,
                   Page.RouteOptions options)
        Routing provides the capability to modify network requests that are made by a page.

        Once routing is enabled, every request matching the url pattern will stall unless it's continued, fulfilled or aborted.

        NOTE: The handler will only be called for the first url if the response is a redirect.

        NOTE: Page.route() will not intercept requests intercepted by Service Worker. See this issue. We recommend disabling Service Workers when using request interception by 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.

        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.
        Since:
        v1.8
      • routeFromHAR

        default void routeFromHAR​(java.nio.file.Path har)
        If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.

        Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to "block".

        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.
        Since:
        v1.23
      • routeFromHAR

        void routeFromHAR​(java.nio.file.Path har,
                          Page.RouteFromHAROptions options)
        If specified the network requests that are made in the page will be served from the HAR file. Read more about Replaying from HAR.

        Playwright will not serve requests intercepted by Service Worker from the HAR file. See this issue. We recommend disabling Service Workers when using request interception by setting Browser.newContext.serviceWorkers to "block".

        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.
        Since:
        v1.23
      • screenshot

        default byte[] screenshot()
        Returns the buffer with the captured screenshot.
        Since:
        v1.8
      • screenshot

        byte[] screenshot​(Page.ScreenshotOptions options)
        Returns the buffer with the captured screenshot.
        Since:
        v1.8
      • selectOption

        default java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                              java.lang.String values)
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

        default java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                              ElementHandle values)
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

        default java.util.List<java.lang.String> selectOption​(java.lang.String selector,
                                                              SelectOption values)
        This method waits for an element matching selector, waits for actionability checks, waits until all specified options are present in the <select> element and selects these options.

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • selectOption

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

        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"});
         
        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.
        Since:
        v1.8
      • setChecked

        default void setChecked​(java.lang.String selector,
                                boolean checked)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        checked - Whether to check or uncheck the checkbox.
        Since:
        v1.15
      • setChecked

        void setChecked​(java.lang.String selector,
                        boolean checked,
                        Page.SetCheckedOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        checked - Whether to check or uncheck the checkbox.
        Since:
        v1.15
      • setContent

        default void setContent​(java.lang.String html)
        This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
        Parameters:
        html - HTML markup to assign to the page.
        Since:
        v1.8
      • setContent

        void setContent​(java.lang.String html,
                        Page.SetContentOptions options)
        This method internally calls document.write(), inheriting all its specific characteristics and behaviors.
        Parameters:
        html - HTML markup to assign to the page.
        Since:
        v1.8
      • setDefaultTimeout

        void setDefaultTimeout​(double timeout)
        This setting will change the default maximum time for all the methods accepting timeout option.

        NOTE: Page.setDefaultNavigationTimeout() takes priority over Page.setDefaultTimeout().

        Parameters:
        timeout - Maximum time in milliseconds
        Since:
        v1.8
      • setExtraHTTPHeaders

        void setExtraHTTPHeaders​(java.util.Map<java.lang.String,​java.lang.String> headers)
        The extra HTTP headers will be sent with every request the page initiates.

        NOTE: Page.setExtraHTTPHeaders() does not guarantee the order of headers in the outgoing requests.

        Parameters:
        headers - An object containing additional HTTP headers to be sent with every request. All header values must be strings.
        Since:
        v1.8
      • setInputFiles

        default void setInputFiles​(java.lang.String selector,
                                   java.nio.file.Path files)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        void setInputFiles​(java.lang.String selector,
                           java.nio.file.Path files,
                           Page.SetInputFilesOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        default void setInputFiles​(java.lang.String selector,
                                   java.nio.file.Path[] files)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        void setInputFiles​(java.lang.String selector,
                           java.nio.file.Path[] files,
                           Page.SetInputFilesOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        default void setInputFiles​(java.lang.String selector,
                                   FilePayload files)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        void setInputFiles​(java.lang.String selector,
                           FilePayload files,
                           Page.SetInputFilesOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        default void setInputFiles​(java.lang.String selector,
                                   FilePayload[] files)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setInputFiles

        void setInputFiles​(java.lang.String selector,
                           FilePayload[] files,
                           Page.SetInputFilesOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • setViewportSize

        void setViewportSize​(int width,
                             int height)
        In the case of multiple pages in a single browser, each page can have its own viewport size. However, Browser.newContext() allows to set viewport size (and more) for all pages in the context at once.

        Page.setViewportSize() will resize the page. A lot of websites don't expect phones to change size, so you should set the viewport size before navigating to the page. Page.setViewportSize() will also 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");
         
        Since:
        v1.8
      • tap

        default void tap​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • tap

        void tap​(java.lang.String selector,
                 Page.TapOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • textContent

        default java.lang.String textContent​(java.lang.String selector)
        Returns element.textContent.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • textContent

        java.lang.String textContent​(java.lang.String selector,
                                     Page.TextContentOptions options)
        Returns element.textContent.
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • title

        java.lang.String title()
        Returns the page's title.
        Since:
        v1.8
      • type

        default void type​(java.lang.String selector,
                          java.lang.String text)
        Deprecated.
        In most cases, you should use Locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.pressSequentially().
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        text - A text to type into a focused element.
        Since:
        v1.8
      • type

        void type​(java.lang.String selector,
                  java.lang.String text,
                  Page.TypeOptions options)
        Deprecated.
        In most cases, you should use Locator.fill() instead. You only need to press keys one by one if there is special keyboard handling on the page - in this case use Locator.pressSequentially().
        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        text - A text to type into a focused element.
        Since:
        v1.8
      • uncheck

        default void uncheck​(java.lang.String selector)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • uncheck

        void uncheck​(java.lang.String selector,
                     Page.UncheckOptions options)
        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.

        Parameters:
        selector - A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used.
        Since:
        v1.8
      • unroute

        default void unroute​(java.lang.String url)
        Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
        Since:
        v1.8
      • unroute

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

        default void unroute​(java.util.regex.Pattern url)
        Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
        Since:
        v1.8
      • unroute

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

        default void unroute​(java.util.function.Predicate<java.lang.String> url)
        Removes a route created with Page.route(). When handler is not specified, removes all routes for the url.
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while routing.
        Since:
        v1.8
      • unroute

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

        java.lang.String url()
        Since:
        v1.8
      • video

        Video video()
        Video object associated with this page.
        Since:
        v1.8
      • waitForClose

        default Page waitForClose​(java.lang.Runnable callback)
        Performs action and waits for the Page to close.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.11
      • waitForClose

        Page waitForClose​(Page.WaitForCloseOptions options,
                          java.lang.Runnable callback)
        Performs action and waits for the Page to close.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.11
      • waitForConsoleMessage

        default ConsoleMessage waitForConsoleMessage​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForConsoleMessage

        ConsoleMessage waitForConsoleMessage​(Page.WaitForConsoleMessageOptions options,
                                             java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForDownload

        default Download waitForDownload​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForDownload

        Download waitForDownload​(Page.WaitForDownloadOptions options,
                                 java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForFileChooser

        default FileChooser waitForFileChooser​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForFileChooser

        FileChooser waitForFileChooser​(Page.WaitForFileChooserOptions options,
                                       java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForFunction

        default JSHandle waitForFunction​(java.lang.String expression,
                                         java.lang.Object arg)
        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);
         
        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.
        Since:
        v1.8
      • waitForFunction

        default JSHandle waitForFunction​(java.lang.String expression)
        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);
         
        Parameters:
        expression - JavaScript expression to be evaluated in the browser context. If the expression evaluates to a function, the function is automatically invoked.
        Since:
        v1.8
      • waitForFunction

        JSHandle waitForFunction​(java.lang.String expression,
                                 java.lang.Object arg,
                                 Page.WaitForFunctionOptions options)
        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);
         
        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.
        Since:
        v1.8
      • waitForLoadState

        default void waitForLoadState​(LoadState state)
        Returns when the required load state has been reached.

        This resolves when the page reaches a required load state, 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.
         
        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.
        Since:
        v1.8
      • waitForLoadState

        default void waitForLoadState()
        Returns when the required load state has been reached.

        This resolves when the page reaches a required load state, 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.
         
        Since:
        v1.8
      • waitForLoadState

        void waitForLoadState​(LoadState state,
                              Page.WaitForLoadStateOptions options)
        Returns when the required load state has been reached.

        This resolves when the page reaches a required load state, 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.
         
        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.
        Since:
        v1.8
      • waitForNavigation

        default Response waitForNavigation​(java.lang.Runnable callback)
        Deprecated.
        This method is inherently racy, please use Page.waitForURL() instead.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForNavigation

        Response waitForNavigation​(Page.WaitForNavigationOptions options,
                                   java.lang.Runnable callback)
        Deprecated.
        This method is inherently racy, please use Page.waitForURL() instead.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForPopup

        default Page waitForPopup​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForPopup

        Page waitForPopup​(Page.WaitForPopupOptions options,
                          java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForRequest

        default Request waitForRequest​(java.lang.String urlOrPredicate,
                                       java.lang.Runnable callback)
        Waits for the matching request and returns it. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next request with the specified url
         Request request = page.waitForRequest("https://example.com/resource", () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
        
         // Waits for the next request matching some conditions
         Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForRequest

        Request waitForRequest​(java.lang.String urlOrPredicate,
                               Page.WaitForRequestOptions options,
                               java.lang.Runnable callback)
        Waits for the matching request and returns it. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next request with the specified url
         Request request = page.waitForRequest("https://example.com/resource", () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
        
         // Waits for the next request matching some conditions
         Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForRequest

        default Request waitForRequest​(java.util.regex.Pattern urlOrPredicate,
                                       java.lang.Runnable callback)
        Waits for the matching request and returns it. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next request with the specified url
         Request request = page.waitForRequest("https://example.com/resource", () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
        
         // Waits for the next request matching some conditions
         Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForRequest

        Request waitForRequest​(java.util.regex.Pattern urlOrPredicate,
                               Page.WaitForRequestOptions options,
                               java.lang.Runnable callback)
        Waits for the matching request and returns it. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next request with the specified url
         Request request = page.waitForRequest("https://example.com/resource", () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
        
         // Waits for the next request matching some conditions
         Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForRequest

        default Request waitForRequest​(java.util.function.Predicate<Request> urlOrPredicate,
                                       java.lang.Runnable callback)
        Waits for the matching request and returns it. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next request with the specified url
         Request request = page.waitForRequest("https://example.com/resource", () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
        
         // Waits for the next request matching some conditions
         Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForRequest

        Request waitForRequest​(java.util.function.Predicate<Request> urlOrPredicate,
                               Page.WaitForRequestOptions options,
                               java.lang.Runnable callback)
        Waits for the matching request and returns it. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next request with the specified url
         Request request = page.waitForRequest("https://example.com/resource", () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
        
         // Waits for the next request matching some conditions
         Request request = page.waitForRequest(request -> "https://example.com".equals(request.url()) && "GET".equals(request.method()), () -> {
           // Triggers the request
           page.getByText("trigger request").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForRequestFinished

        default Request waitForRequestFinished​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.12
      • waitForRequestFinished

        Request waitForRequestFinished​(Page.WaitForRequestFinishedOptions options,
                                       java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.12
      • waitForResponse

        default Response waitForResponse​(java.lang.String urlOrPredicate,
                                         java.lang.Runnable callback)
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForResponse

        Response waitForResponse​(java.lang.String urlOrPredicate,
                                 Page.WaitForResponseOptions options,
                                 java.lang.Runnable callback)
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForResponse

        default Response waitForResponse​(java.util.regex.Pattern urlOrPredicate,
                                         java.lang.Runnable callback)
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForResponse

        Response waitForResponse​(java.util.regex.Pattern urlOrPredicate,
                                 Page.WaitForResponseOptions options,
                                 java.lang.Runnable callback)
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForResponse

        default Response waitForResponse​(java.util.function.Predicate<Response> urlOrPredicate,
                                         java.lang.Runnable callback)
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForResponse

        Response waitForResponse​(java.util.function.Predicate<Response> urlOrPredicate,
                                 Page.WaitForResponseOptions options,
                                 java.lang.Runnable callback)
        Returns the matched response. See waiting for event for more details about events.

        **Usage**

        
         // Waits for the next response with the specified url
         Response response = page.waitForResponse("https://example.com/resource", () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
        
         // Waits for the next response matching some conditions
         Response response = page.waitForResponse(response -> "https://example.com".equals(response.url()) && response.status() == 200, () -> {
           // Triggers the response
           page.getByText("trigger response").click();
         });
         
        Parameters:
        urlOrPredicate - Request URL string, regex or predicate 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.
        callback - Callback that performs the action triggering the event.
        Since:
        v1.8
      • waitForSelector

        default ElementHandle waitForSelector​(java.lang.String selector)
        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();
             }
           }
         }
         
        Parameters:
        selector - A selector to query for.
        Since:
        v1.8
      • waitForSelector

        ElementHandle waitForSelector​(java.lang.String selector,
                                      Page.WaitForSelectorOptions options)
        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();
             }
           }
         }
         
        Parameters:
        selector - A selector to query for.
        Since:
        v1.8
      • waitForCondition

        default void waitForCondition​(java.util.function.BooleanSupplier condition)
        The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.

        **Usage**

        Use the method to wait for a condition that depends on page events:

        
         List<String> messages = new ArrayList<>();
         page.onConsoleMessage(m -> messages.add(m.text()));
         page.getByText("Submit button").click();
         page.waitForCondition(() -> messages.size() > 3);
         
        Parameters:
        condition - Condition to wait for.
        Since:
        v1.32
      • waitForCondition

        void waitForCondition​(java.util.function.BooleanSupplier condition,
                              Page.WaitForConditionOptions options)
        The method will block until the condition returns true. All Playwright events will be dispatched while the method is waiting for the condition.

        **Usage**

        Use the method to wait for a condition that depends on page events:

        
         List<String> messages = new ArrayList<>();
         page.onConsoleMessage(m -> messages.add(m.text()));
         page.getByText("Submit button").click();
         page.waitForCondition(() -> messages.size() > 3);
         
        Parameters:
        condition - Condition to wait for.
        Since:
        v1.32
      • waitForTimeout

        void waitForTimeout​(double timeout)
        Waits for the 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);
         
        Parameters:
        timeout - A timeout to wait for
        Since:
        v1.8
      • waitForURL

        default void waitForURL​(java.lang.String url)
        Waits for the main frame to navigate to the given URL.

        **Usage**

        
         page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
         page.waitForURL("**\/target.html");
         
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
        Since:
        v1.11
      • waitForURL

        void waitForURL​(java.lang.String url,
                        Page.WaitForURLOptions options)
        Waits for the main frame to navigate to the given URL.

        **Usage**

        
         page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
         page.waitForURL("**\/target.html");
         
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
        Since:
        v1.11
      • waitForURL

        default void waitForURL​(java.util.regex.Pattern url)
        Waits for the main frame to navigate to the given URL.

        **Usage**

        
         page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
         page.waitForURL("**\/target.html");
         
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
        Since:
        v1.11
      • waitForURL

        void waitForURL​(java.util.regex.Pattern url,
                        Page.WaitForURLOptions options)
        Waits for the main frame to navigate to the given URL.

        **Usage**

        
         page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
         page.waitForURL("**\/target.html");
         
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
        Since:
        v1.11
      • waitForURL

        default void waitForURL​(java.util.function.Predicate<java.lang.String> url)
        Waits for the main frame to navigate to the given URL.

        **Usage**

        
         page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
         page.waitForURL("**\/target.html");
         
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
        Since:
        v1.11
      • waitForURL

        void waitForURL​(java.util.function.Predicate<java.lang.String> url,
                        Page.WaitForURLOptions options)
        Waits for the main frame to navigate to the given URL.

        **Usage**

        
         page.click("a.delayed-navigation"); // Clicking the link will indirectly cause a navigation
         page.waitForURL("**\/target.html");
         
        Parameters:
        url - A glob pattern, regex pattern or predicate receiving [URL] to match while waiting for the navigation. Note that if the parameter is a string without wildcard characters, the method will wait for navigation to URL that is exactly equal to the string.
        Since:
        v1.11
      • waitForWebSocket

        default WebSocket waitForWebSocket​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForWebSocket

        WebSocket waitForWebSocket​(Page.WaitForWebSocketOptions options,
                                   java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForWorker

        default Worker waitForWorker​(java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • waitForWorker

        Worker waitForWorker​(Page.WaitForWorkerOptions options,
                             java.lang.Runnable callback)
        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.
        Parameters:
        callback - Callback that performs the action triggering the event.
        Since:
        v1.9
      • workers

        java.util.List<Worker> workers()
        This method returns all of the dedicated WebWorkers associated with the page.

        NOTE: This does not contain ServiceWorkers

        Since:
        v1.8