Interface Driver

All Superinterfaces:
CoreDriver, io.karatelabs.js.ObjectLike, io.karatelabs.js.SimpleObject
All Known Implementing Classes:
CdpDriver, W3cDriver

public interface Driver extends CoreDriver, io.karatelabs.js.SimpleObject
Browser automation driver interface. Provides a unified API for browser automation across different backends (CDP, Playwright, WebDriver).

This interface extends CoreDriver which defines the ~12 primitive operations. Most methods in this interface are convenience methods that delegate to those primitives, primarily to CoreDriver.eval(String).

Phase 8: Extracted from CdpDriver to enable multi-backend support.

Phase 9: Implements ObjectLike for Gherkin/DSL integration (JS property access).

Phase 10: Extends CoreDriver to clearly separate primitives from convenience methods.

See Also:
  • Method Details

    • jsGet

      default Object jsGet(String name)
      Get a property value or method by name for JavaScript access. Properties return values directly; methods return JavaCallables.
      Specified by:
      jsGet in interface io.karatelabs.js.SimpleObject
    • putMember

      default void putMember(String name, Object value)
      Set a property value by name for JavaScript assignment. Supports: driver.url = '...', driver.dimensions = {...}
      Specified by:
      putMember in interface io.karatelabs.js.ObjectLike
      Specified by:
      putMember in interface io.karatelabs.js.SimpleObject
    • eval

      default Object eval(String js)
      Execute JavaScript. Delegates to script(String).
      Specified by:
      eval in interface CoreDriver
      Parameters:
      js - JavaScript expression to execute
      Returns:
      the result of the JavaScript execution
    • eval

      default Object eval(Object expression)
      Execute JavaScript with support for JsFunction. Delegates to script(Object).
      Parameters:
      expression - JavaScript expression as String or JsFunction
      Returns:
      the result of the JavaScript execution
    • frame

      default void frame(Object target)
      Switch frames. Dispatches to switchFrame(int) or switchFrame(String).
      Specified by:
      frame in interface CoreDriver
      Parameters:
      target - frame identifier: - null to return to main frame - Integer for frame index - String for frame locator
    • window

      default void window(String operation)
      Window management. Dispatches to maximize(), minimize(), fullscreen().
      Specified by:
      window in interface CoreDriver
      Parameters:
      operation - one of: "maximize", "minimize", "fullscreen", "normal"
    • tab

      default void tab(Object target)
      Tab switching. Dispatches to switchPage(int) or switchPage(String).
      Specified by:
      tab in interface CoreDriver
      Parameters:
      target - tab identifier: - Integer for tab index - String for title or URL substring match
    • setUrl

      void setUrl(String url)
      Navigate to URL and wait for page load.
    • getUrl

      String getUrl()
      Get current URL.
    • getTitle

      String getTitle()
      Get page title.
    • waitForPageLoad

      void waitForPageLoad(PageLoadStrategy strategy)
      Wait for page to load based on strategy.
    • waitForPageLoad

      void waitForPageLoad(PageLoadStrategy strategy, Duration timeout)
      Wait for page to load with custom timeout.
    • refresh

      void refresh()
      Refresh the current page.
    • reload

      void reload()
      Reload the page ignoring cache.
    • back

      void back()
      Navigate back in history.
    • forward

      void forward()
      Navigate forward in history.
    • script

      Object script(String expression)
      Execute JavaScript and return result.
    • script

      default Object script(Object expression)
      Execute JavaScript with support for JsFunction. If the argument is a JsFunction (e.g., arrow function), it will be serialized to its source code and invoked as an IIFE.

      Examples:

       script("document.title")                    // string expression
       script(() => document.title)                // arrow function (from Karate JS)
       script(() => { return document.title })     // arrow function with block body
       
      Parameters:
      expression - JavaScript expression as String or JsFunction
      Returns:
      the result of the JavaScript execution
    • script

      default Object script(String locator, Object expression)
      Execute a script on an element. The element is available as '_' in the expression. Expression can be a String ("_.value") or JsFunction (_ => _.value).
    • scriptAll

      default List<Object> scriptAll(String locator, Object expression)
      Execute a script on all matching elements. Each element is available as '_' in the expression. Expression can be a String or JsFunction.
    • screenshot

      byte[] screenshot()
      Take screenshot and return PNG bytes.
      Specified by:
      screenshot in interface CoreDriver
      Returns:
      PNG image bytes
    • screenshot

      byte[] screenshot(boolean embed)
      Take screenshot, optionally embed in report.
    • screenshot

      default byte[] screenshot(String locator)
      Take a screenshot of a specific element (clipped to its bounding rect). Default impl falls back to full-page screenshot — backends may override for native element-clipped capture.
    • screenshot

      default byte[] screenshot(String locator, boolean embed)
      Take a screenshot of a specific element, optionally embed in report. Default impl falls back to full-page screenshot.
    • failureScreenshot

      default byte[] failureScreenshot()
      Best-effort screenshot for the failure path (screenshotOnFailure). MUST be bounded by a SHORT timeout so a stalled renderer can't turn a swallowed diagnostic capture into a long hang.

      Why this is separate from screenshot(boolean): the regular API uses the full operation timeout because a user explicitly asked for the image. The failure path is the opposite — the scenario has already failed, the bytes are best-effort, and the capture is wrapped in a catch-and-continue. Yet it inherited the same long timeout, so a renderer that stalled (seen in CI as "CDP timeout for: Page.captureScreenshot" under a slow container) made every failed scenario pay the full timeout for an image it then discards — widening a brief renderer blip into a long cascade. The default delegates to screenshot(false); CDP overrides with a short CDP timeout.

    • onDialog

      void onDialog(DialogHandler handler)
      Register a handler for JavaScript dialogs (alert, confirm, prompt, beforeunload).
    • getDialogText

      String getDialogText()
      Get the current dialog message.
    • dialog

      void dialog(boolean accept)
      Accept or dismiss the current dialog.
    • dialog

      void dialog(boolean accept, String input)
      Accept or dismiss the current dialog with optional prompt input.
      Specified by:
      dialog in interface CoreDriver
      Parameters:
      accept - true to accept (OK), false to dismiss (Cancel)
      input - text for prompt dialogs (ignored if accept is false)
    • getDialog

      Dialog getDialog()
      Get the current dialog if one is open. This is useful for detecting dialogs that appear after actions.
      Returns:
      the current Dialog, or null if no dialog is open
    • switchFrame

      void switchFrame(int index)
      Switch to an iframe by index.
    • switchFrame

      void switchFrame(String locator)
      Switch to an iframe by locator, or null to return to main frame.
    • getCurrentFrame

      Map<String,Object> getCurrentFrame()
      Get the current frame info, or null if in main frame.
    • submit

      default Driver submit()
      Mark the next action as triggering a page navigation. After the next click/action, the driver will wait for the page to change (detected by URL or document element hash change).

      Works on all backends (CDP, WebDriver, Playwright).

      Usage: submit().click('#button')

    • waitIfSubmitRequested

      default void waitIfSubmitRequested()
      If submit() was called, wait for the document to change after running the action.
    • click

      default Element click(String locator)
      Click an element.
    • focus

      default Element focus(String locator)
      Focus an element.
    • clear

      default Element clear(String locator)
      Clear an input element.
    • input

      default Element input(String locator, String value)
      Input text into an element (focus, clear, type). For time/date inputs that don't respond to CDP keystrokes, uses JS value assignment.
    • input

      default Element input(String locator, String[] values)
      Input a sequence of values (strings and/or special keys) into an element. Each value is sent in sequence — supports mixing literal text with Key.ENTER, Key.TAB etc. so that an array form like input('#search', ['hello', Key.ENTER]) matches v1.
    • input

      default Element input(String locator, String chars, int delay)
      Input characters one-by-one with a delay between each — useful for simulating slow human typing or bypassing race conditions in handlers that debounce keypresses.
    • input

      default Element input(String locator, String[] values, int delay)
      Input an array of values with a delay between each.
    • value

      default Element value(String locator, String value)
      Set the value of an input element directly.
    • select

      default Element select(String locator, String text)
      Select an option from a dropdown by text or value.
    • select

      default Element select(String locator, int index)
      Select an option from a dropdown by index.
    • scroll

      default Element scroll(String locator)
      Scroll an element into view.
    • highlight

      default Element highlight(String locator)
      Highlight an element (for debugging).
    • highlight

      default Element highlight(String locator, int millis)
      Highlight an element (for debugging) for a specific duration in millis.
    • highlightAll

      default void highlightAll(String locator)
      Highlight all elements matching the locator (for debugging).
    • highlightAll

      default void highlightAll(String locator, int millis)
      Highlight all elements matching the locator for a specific duration in millis.
    • text

      default String text(String locator)
      Get the text content of an element.
    • html

      default String html(String locator)
      Get the outer HTML of an element.
    • value

      default String value(String locator)
      Get the value of an input element.
    • attribute

      default String attribute(String locator, String name)
      Get an attribute of an element.
    • property

      default Object property(String locator, String name)
      Get a property of an element.
    • enabled

      default boolean enabled(String locator)
      Check if an element is enabled.
    • exists

      default boolean exists(String locator)
      Check if an element exists.
    • position

      default Map<String,Object> position(String locator)
      Get the position of an element (absolute).
    • position

      default Map<String,Object> position(String locator, boolean relative)
      Get the position of an element.
      Parameters:
      relative - if true, returns viewport-relative position
    • locate

      default Element locate(String locator)
      Find an element by locator. This is a convenience method that creates an Element wrapper.
    • locateAll

      List<Element> locateAll(String locator)
      Find all elements matching a locator. Implementation requires driver-specific indexed locator support.
    • locateAll

      default List<Element> locateAll(String locator, Predicate<Element> predicate)
      Find all elements matching a locator and filter via the supplied predicate. Java-only convenience — useful for reporting/auditing where you need to narrow locateAll(String) results without re-querying the DOM.
    • scriptAll

      default List<Object> scriptAll(String locator, Object expression, Predicate<Object> predicate)
      Run an element-bound JS expression on every match and filter the resulting values via the predicate. Java-only convenience.
    • optional

      default Element optional(String locator)
      Find an element that may not exist (optional). This is a convenience method that creates an optional Element wrapper.
    • waitFor

      Element waitFor(String locator)
      Wait for an element to exist.
    • waitFor

      Element waitFor(String locator, Duration timeout)
      Wait for an element to exist with custom timeout.
    • waitForAny

      Element waitForAny(String locator1, String locator2)
      Wait for any of the locators to match.
    • waitForAny

      Element waitForAny(String[] locators)
      Wait for any of the locators to match.
    • waitForAny

      Element waitForAny(String[] locators, Duration timeout)
      Wait for any of the locators to match with custom timeout.
    • waitForText

      Element waitForText(String locator, String expected)
      Wait for an element to contain specific text.
    • waitForText

      Element waitForText(String locator, String expected, Duration timeout)
      Wait for an element to contain specific text with custom timeout.
    • waitForEnabled

      Element waitForEnabled(String locator)
      Wait for an element to be enabled.
    • waitForEnabled

      Element waitForEnabled(String locator, Duration timeout)
      Wait for an element to be enabled with custom timeout.
    • waitForUrl

      String waitForUrl(String expected)
      Wait for URL to contain expected string.
    • waitForUrl

      String waitForUrl(String expected, Duration timeout)
      Wait for URL to contain expected string with custom timeout.
    • waitUntil

      Element waitUntil(String locator, String expression)
      Wait until a JavaScript expression on an element evaluates to truthy.
    • waitUntil

      Element waitUntil(String locator, String expression, Duration timeout)
      Wait until a JavaScript expression on an element evaluates to truthy.
    • waitUntil

      boolean waitUntil(String expression)
      Wait until a JavaScript expression evaluates to truthy.
    • waitUntil

      boolean waitUntil(String expression, Duration timeout)
      Wait until a JavaScript expression evaluates to truthy with custom timeout.
    • waitUntil

      Object waitUntil(Supplier<Object> condition)
      Wait until a supplier returns a truthy value.
    • waitUntil

      Object waitUntil(Supplier<Object> condition, Duration timeout)
      Wait until a supplier returns a truthy value with custom timeout.
    • waitForResultCount

      List<Element> waitForResultCount(String locator, int count)
      Wait for a specific number of elements to match.
    • waitForResultCount

      List<Element> waitForResultCount(String locator, int count, Duration timeout)
      Wait for a specific number of elements to match with custom timeout.
    • waitForResultCount

      default List<Object> waitForResultCount(String locator, int count, String expression)
      Wait until scriptAll(String, Object) returns exactly count results when run against the supplied JS expression on each matched element. Java-only convenience overload (v1 parity).
    • cookie

      Map<String,Object> cookie(String name)
      Get a cookie by name.
      Specified by:
      cookie in interface CoreDriver
      Parameters:
      name - the cookie name
      Returns:
      the cookie as a Map, or null if not found
    • cookie

      void cookie(Map<String,Object> cookie)
      Set a cookie.
      Specified by:
      cookie in interface CoreDriver
      Parameters:
      cookie - the cookie as a Map with keys: name, value, domain, path, etc.
    • deleteCookie

      void deleteCookie(String name)
      Delete a cookie by name.
    • clearCookies

      void clearCookies()
      Clear all cookies.
    • getCookies

      List<Map<String,Object>> getCookies()
      Get all cookies.
    • setCookies

      default void setCookies(List<Map<String,Object>> cookies)
      Bulk-set cookies — convenience over repeated cookie(Map) calls. Mirrors v1's setCookies, where a JSON array could be loaded from a file and applied wholesale.
    • maximize

      void maximize()
      Maximize the browser window.
    • minimize

      void minimize()
      Minimize the browser window.
    • fullscreen

      void fullscreen()
      Make the browser window fullscreen.
    • getDimensions

      Map<String,Object> getDimensions()
      Get window dimensions and position.
    • setDimensions

      void setDimensions(Map<String,Object> dimensions)
      Set window dimensions and/or position.
    • activate

      void activate()
      Activate the browser window (bring to front).
    • pdf

      byte[] pdf(Map<String,Object> options)
      Generate a PDF of the current page.
      Specified by:
      pdf in interface CoreDriver
      Parameters:
      options - PDF options (scale, landscape, margins, etc.), or null for defaults
      Returns:
      PDF bytes
    • pdf

      byte[] pdf()
      Generate a PDF of the current page with default options.
    • mouse

      Mouse mouse()
      Get a Mouse object at position (0, 0).
      Specified by:
      mouse in interface CoreDriver
      Returns:
      a new Mouse object at position (0, 0)
    • mouse

      Mouse mouse(String locator)
      Get a Mouse object positioned at an element's center.
    • mouse

      Mouse mouse(Number x, Number y)
      Get a Mouse object at specified coordinates.
    • keys

      Keys keys()
      Get a Keys object for keyboard input.
      Specified by:
      keys in interface CoreDriver
      Returns:
      the Keys object for typing and key events
    • getPages

      List<String> getPages()
      Get list of all page targets (tabs).
    • switchPage

      void switchPage(String titleOrUrl)
      Switch to a page by title or URL substring.
    • switchPage

      void switchPage(int index)
      Switch to a page by index.
    • switchPageById

      default void switchPageById(String targetId)
      Switch to a page by its backend target ID.

      Useful in conjunction with drainOpenedTargets() — the drained entries carry a targetId which unambiguously identifies the new tab, while URL/title can be ambiguous (e.g. blank or duplicated across tabs).

      Default implementation delegates to switchPage(String) using the target ID as a substring match; most drivers should override.

    • drainOpenedTargets

      default List<Map<String,Object>> drainOpenedTargets()
      Drain and return the list of new page targets (tabs) opened since the last call.

      Event-driven — no CDP round-trip. Each entry is a map with targetId, url, and title. Returns an empty list if nothing new was opened.

      Use case: an automation that clicks a link with target="_blank" or a button that calls window.open() can call this after the click to learn whether (and where) a new tab appeared, and then call switchPage(String) or switchPage(int) to focus it.

      Mirrors the getDialog() pattern — the driver pushes events into an internal queue and the caller drains it, avoiding polling Target.getTargets after every action.

      Default implementation returns an empty list for drivers that don't track target events.

    • rightOf

      default Finder rightOf(String locator)
      Create a finder for elements to the right of the reference element. This is a convenience method that creates a Finder.
    • leftOf

      default Finder leftOf(String locator)
      Create a finder for elements to the left of the reference element. This is a convenience method that creates a Finder.
    • above

      default Finder above(String locator)
      Create a finder for elements above the reference element. This is a convenience method that creates a Finder.
    • below

      default Finder below(String locator)
      Create a finder for elements below the reference element. This is a convenience method that creates a Finder.
    • near

      default Finder near(String locator)
      Create a finder for elements near the reference element. This is a convenience method that creates a Finder.
    • timeout

      default Driver timeout(int millis)
      Set the operation timeout in milliseconds for this driver instance. Returns the driver for chaining (v1 parity, e.g. timeout(5000).click(...)).
    • timeout

      default int timeout()
      Get the current operation timeout in milliseconds.
    • delay

      default Driver delay(int millis)
      Sleep for the given milliseconds. Returns the driver for chaining (v1 parity, e.g. delay(500).click(...)).
    • intercept

      void intercept(List<String> patterns, InterceptHandler handler)
      Enable request interception with a handler.
      Specified by:
      intercept in interface CoreDriver
      Parameters:
      patterns - URL patterns to intercept (e.g., "*api/*")
      handler - the intercept handler (return InterceptResponse to mock, null to continue)
    • intercept

      void intercept(InterceptHandler handler)
      Enable request interception for all requests.
    • stopIntercept

      void stopIntercept()
      Stop request interception.
    • quit

      void quit()
      Close driver and browser.
      Specified by:
      quit in interface CoreDriver
    • close

      void close()
      Alias for quit().
    • isTerminated

      boolean isTerminated()
      Check if driver is terminated.
      Specified by:
      isTerminated in interface CoreDriver
    • isResponsive

      default boolean isResponsive()
      Quick health check — returns false if the driver's underlying protocol channel (CDP websocket, WebDriver session, etc.) is stuck or unresponsive. MUST use a short timeout so the caller doesn't block on a poisoned driver.

      Used by PooledDriverProvider to decide whether a driver can be returned to the pool safely. The default here returns true (backends that can't cheaply probe the channel are assumed healthy). CDP overrides with a bounded Runtime.evaluate.

    • isReady

      default boolean isReady()
      Whether the driver is ready to accept script/element calls right now — i.e. the page's execution context is live (not mid-navigation / mid-tab-switch). Cheap and non-blocking. Backends without an explicit readiness signal report true.
    • waitUntilReady

      default void waitUntilReady()
      Block until the driver is ready to accept calls (execution context live), or the configured timeout elapses. Idempotent and safe to call when already ready (returns immediately). Intended for clients, pools, and providers that want an explicit barrier before driving — e.g. PooledDriverProvider after acquiring/reusing a driver, so a scenario's first call never races a not-yet-ready context. The default is a no-op for backends that establish readiness synchronously.
    • getOptions

      DriverOptions getOptions()
      Get driver options.
      Specified by:
      getOptions in interface CoreDriver