Interface Driver
- All Superinterfaces:
CoreDriver,io.karatelabs.js.ObjectLike,io.karatelabs.js.SimpleObject
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:
-
Field Summary
Fields inherited from interface io.karatelabs.js.SimpleObject
logger, TO_STRING -
Method Summary
Modifier and TypeMethodDescriptiondefault FinderCreate a finder for elements above the reference element.voidactivate()Activate the browser window (bring to front).default StringGet an attribute of an element.voidback()Navigate back in history.default FinderCreate a finder for elements below the reference element.default ElementClear an input element.voidClear all cookies.default ElementClick an element.voidclose()Alias for quit().Get a cookie by name.voidSet a cookie.default Driverdelay(int millis) Sleep for the given milliseconds.voiddeleteCookie(String name) Delete a cookie by name.voiddialog(boolean accept) Accept or dismiss the current dialog.voidAccept or dismiss the current dialog with optional prompt input.Drain and return the list of new page targets (tabs) opened since the last call.default booleanCheck if an element is enabled.default ObjectExecute JavaScript with support for JsFunction.default ObjectExecute JavaScript.default booleanCheck if an element exists.default byte[]Best-effort screenshot for the failure path (screenshotOnFailure).default ElementFocus an element.voidforward()Navigate forward in history.default voidSwitch frames.voidMake the browser window fullscreen.Get all cookies.Get the current frame info, or null if in main frame.Get the current dialog if one is open.Get the current dialog message.Get window dimensions and position.Get driver options.getPages()Get list of all page targets (tabs).getTitle()Get page title.getUrl()Get current URL.default ElementHighlight an element (for debugging).default ElementHighlight an element (for debugging) for a specific duration in millis.default voidhighlightAll(String locator) Highlight all elements matching the locator (for debugging).default voidhighlightAll(String locator, int millis) Highlight all elements matching the locator for a specific duration in millis.default StringGet the outer HTML of an element.default ElementInput text into an element (focus, clear, type).default ElementInput a sequence of values (strings and/or special keys) into an element.default ElementInput an array of values with a delay between each.default ElementInput characters one-by-one with a delay between each — useful for simulating slow human typing or bypassing race conditions in handlers that debounce keypresses.voidintercept(InterceptHandler handler) Enable request interception for all requests.voidintercept(List<String> patterns, InterceptHandler handler) Enable request interception with a handler.default booleanisReady()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).default booleanQuick health check — returns false if the driver's underlying protocol channel (CDP websocket, WebDriver session, etc.) is stuck or unresponsive.booleanCheck if driver is terminated.default ObjectGet a property value or method by name for JavaScript access.keys()Get a Keys object for keyboard input.default FinderCreate a finder for elements to the left of the reference element.default ElementFind an element by locator.Find all elements matching a locator.Find all elements matching a locator and filter via the supplied predicate.voidmaximize()Maximize the browser window.voidminimize()Minimize the browser window.mouse()Get a Mouse object at position (0, 0).Get a Mouse object at specified coordinates.Get a Mouse object positioned at an element's center.default voidNavigate to URL.default FinderCreate a finder for elements near the reference element.voidonDialog(DialogHandler handler) Register a handler for JavaScript dialogs (alert, confirm, prompt, beforeunload).default ElementFind an element that may not exist (optional).byte[]pdf()Generate a PDF of the current page with default options.byte[]Generate a PDF of the current page.Get the position of an element (absolute).Get the position of an element.default ObjectGet a property of an element.default voidSet a property value by name for JavaScript assignment.voidquit()Close driver and browser.voidrefresh()Refresh the current page.voidreload()Reload the page ignoring cache.default FinderCreate a finder for elements to the right of the reference element.byte[]Take screenshot and return PNG bytes.byte[]screenshot(boolean embed) Take screenshot, optionally embed in report.default byte[]screenshot(String locator) Take a screenshot of a specific element (clipped to its bounding rect).default byte[]screenshot(String locator, boolean embed) Take a screenshot of a specific element, optionally embed in report.default ObjectExecute JavaScript with support for JsFunction.Execute JavaScript and return result.default ObjectExecute a script on an element.Execute a script on all matching elements.Run an element-bound JS expression on every match and filter the resulting values via the predicate.default ElementScroll an element into view.default ElementSelect an option from a dropdown by index.default ElementSelect an option from a dropdown by text or value.default voidsetCookies(List<Map<String, Object>> cookies) Bulk-set cookies — convenience over repeatedcookie(Map)calls.voidsetDimensions(Map<String, Object> dimensions) Set window dimensions and/or position.voidNavigate to URL and wait for page load.voidStop request interception.default Driversubmit()Mark the next action as triggering a page navigation.voidswitchFrame(int index) Switch to an iframe by index.voidswitchFrame(String locator) Switch to an iframe by locator, or null to return to main frame.voidswitchPage(int index) Switch to a page by index.voidswitchPage(String titleOrUrl) Switch to a page by title or URL substring.default voidswitchPageById(String targetId) Switch to a page by its backend target ID.default voidTab switching.default StringGet the text content of an element.default inttimeout()Get the current operation timeout in milliseconds.default Drivertimeout(int millis) Set the operation timeout in milliseconds for this driver instance.default StringGet the value of an input element.default ElementSet the value of an input element directly.Wait for an element to exist.Wait for an element to exist with custom timeout.waitForAny(String[] locators) Wait for any of the locators to match.waitForAny(String[] locators, Duration timeout) Wait for any of the locators to match with custom timeout.waitForAny(String locator1, String locator2) Wait for any of the locators to match.waitForEnabled(String locator) Wait for an element to be enabled.waitForEnabled(String locator, Duration timeout) Wait for an element to be enabled with custom timeout.voidwaitForPageLoad(PageLoadStrategy strategy) Wait for page to load based on strategy.voidwaitForPageLoad(PageLoadStrategy strategy, Duration timeout) Wait for page to load with custom timeout.waitForResultCount(String locator, int count) Wait for a specific number of elements to match.waitForResultCount(String locator, int count, String expression) Wait untilscriptAll(String, Object)returns exactlycountresults when run against the supplied JS expression on each matched element.waitForResultCount(String locator, int count, Duration timeout) Wait for a specific number of elements to match with custom timeout.waitForText(String locator, String expected) Wait for an element to contain specific text.waitForText(String locator, String expected, Duration timeout) Wait for an element to contain specific text with custom timeout.waitForUrl(String expected) Wait for URL to contain expected string.waitForUrl(String expected, Duration timeout) Wait for URL to contain expected string with custom timeout.default voidIf submit() was called, wait for the document to change after running the action.booleanWait until a JavaScript expression evaluates to truthy.Wait until a JavaScript expression on an element evaluates to truthy.Wait until a JavaScript expression on an element evaluates to truthy.booleanWait until a JavaScript expression evaluates to truthy with custom timeout.Wait until a supplier returns a truthy value.Wait until a supplier returns a truthy value with custom timeout.default voidBlock until the driver is ready to accept calls (execution context live), or the configured timeout elapses.default voidWindow management.Methods inherited from interface io.karatelabs.js.ObjectLike
getMember, getPrototype, isExtensible, isFrozen, isOwnProperty, isSealed, putMember, removeMember, setExtensible, setFrozen, setSealedMethods inherited from interface io.karatelabs.js.SimpleObject
getMember, jsKeys, jsToString, removeMember, toMap
-
Method Details
-
jsGet
Get a property value or method by name for JavaScript access. Properties return values directly; methods return JavaCallables.- Specified by:
jsGetin interfaceio.karatelabs.js.SimpleObject
-
putMember
Set a property value by name for JavaScript assignment. Supports: driver.url = '...', driver.dimensions = {...}- Specified by:
putMemberin interfaceio.karatelabs.js.ObjectLike- Specified by:
putMemberin interfaceio.karatelabs.js.SimpleObject
-
eval
Execute JavaScript. Delegates toscript(String).- Specified by:
evalin interfaceCoreDriver- Parameters:
js- JavaScript expression to execute- Returns:
- the result of the JavaScript execution
-
eval
Execute JavaScript with support for JsFunction. Delegates toscript(Object).- Parameters:
expression- JavaScript expression as String or JsFunction- Returns:
- the result of the JavaScript execution
-
frame
Switch frames. Dispatches toswitchFrame(int)orswitchFrame(String).- Specified by:
framein interfaceCoreDriver- Parameters:
target- frame identifier: -nullto return to main frame -Integerfor frame index -Stringfor frame locator
-
window
Window management. Dispatches to maximize(), minimize(), fullscreen().- Specified by:
windowin interfaceCoreDriver- Parameters:
operation- one of: "maximize", "minimize", "fullscreen", "normal"
-
tab
Tab switching. Dispatches toswitchPage(int)orswitchPage(String).- Specified by:
tabin interfaceCoreDriver- Parameters:
target- tab identifier: -Integerfor tab index -Stringfor title or URL substring match
-
setUrl
Navigate to URL and wait for page load. -
getUrl
String getUrl()Get current URL. -
getTitle
String getTitle()Get page title. -
waitForPageLoad
Wait for page to load based on strategy. -
waitForPageLoad
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
Execute JavaScript and return result. -
script
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
Execute a script on an element. The element is available as '_' in the expression. Expression can be a String ("_.value") or JsFunction (_ => _.value). -
scriptAll
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:
screenshotin interfaceCoreDriver- Returns:
- PNG image bytes
-
screenshot
byte[] screenshot(boolean embed) Take screenshot, optionally embed in report. -
screenshot
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
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 toscreenshot(false); CDP overrides with a short CDP timeout. -
onDialog
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
Accept or dismiss the current dialog with optional prompt input.- Specified by:
dialogin interfaceCoreDriver- 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
Switch to an iframe by locator, or null to return to main frame. -
getCurrentFrame
Get the current frame info, or null if in main frame. -
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
Click an element. -
focus
Focus an element. -
clear
Clear an input element. -
input
Input text into an element (focus, clear, type). For time/date inputs that don't respond to CDP keystrokes, uses JS value assignment. -
input
Input a sequence of values (strings and/or special keys) into an element. Each value is sent in sequence — supports mixing literal text withKey.ENTER,Key.TABetc. so that an array form likeinput('#search', ['hello', Key.ENTER])matches v1. -
input
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
Input an array of values with a delay between each. -
value
Set the value of an input element directly. -
select
Select an option from a dropdown by text or value. -
select
Select an option from a dropdown by index. -
scroll
Scroll an element into view. -
highlight
Highlight an element (for debugging). -
highlight
Highlight an element (for debugging) for a specific duration in millis. -
highlightAll
Highlight all elements matching the locator (for debugging). -
highlightAll
Highlight all elements matching the locator for a specific duration in millis. -
text
Get the text content of an element. -
html
Get the outer HTML of an element. -
value
Get the value of an input element. -
attribute
Get an attribute of an element. -
property
Get a property of an element. -
enabled
Check if an element is enabled. -
exists
Check if an element exists. -
position
Get the position of an element (absolute). -
position
Get the position of an element.- Parameters:
relative- if true, returns viewport-relative position
-
locate
Find an element by locator. This is a convenience method that creates an Element wrapper. -
locateAll
Find all elements matching a locator. Implementation requires driver-specific indexed locator support. -
locateAll
Find all elements matching a locator and filter via the supplied predicate. Java-only convenience — useful for reporting/auditing where you need to narrowlocateAll(String)results without re-querying the DOM. -
scriptAll
Run an element-bound JS expression on every match and filter the resulting values via the predicate. Java-only convenience. -
optional
Find an element that may not exist (optional). This is a convenience method that creates an optional Element wrapper. -
waitFor
Wait for an element to exist. -
waitFor
Wait for an element to exist with custom timeout. -
waitForAny
Wait for any of the locators to match. -
waitForAny
Wait for any of the locators to match. -
waitForAny
Wait for any of the locators to match with custom timeout. -
waitForText
Wait for an element to contain specific text. -
waitForText
Wait for an element to contain specific text with custom timeout. -
waitForEnabled
Wait for an element to be enabled. -
waitForEnabled
Wait for an element to be enabled with custom timeout. -
waitForUrl
Wait for URL to contain expected string. -
waitForUrl
Wait for URL to contain expected string with custom timeout. -
waitUntil
Wait until a JavaScript expression on an element evaluates to truthy. -
waitUntil
Wait until a JavaScript expression on an element evaluates to truthy. -
waitUntil
Wait until a JavaScript expression evaluates to truthy. -
waitUntil
Wait until a JavaScript expression evaluates to truthy with custom timeout. -
waitUntil
Wait until a supplier returns a truthy value. -
waitUntil
Wait until a supplier returns a truthy value with custom timeout. -
waitForResultCount
Wait for a specific number of elements to match. -
waitForResultCount
Wait for a specific number of elements to match with custom timeout. -
waitForResultCount
Wait untilscriptAll(String, Object)returns exactlycountresults when run against the supplied JS expression on each matched element. Java-only convenience overload (v1 parity). -
cookie
Get a cookie by name.- Specified by:
cookiein interfaceCoreDriver- Parameters:
name- the cookie name- Returns:
- the cookie as a Map, or null if not found
-
cookie
Set a cookie.- Specified by:
cookiein interfaceCoreDriver- Parameters:
cookie- the cookie as a Map with keys: name, value, domain, path, etc.
-
deleteCookie
Delete a cookie by name. -
clearCookies
void clearCookies()Clear all cookies. -
getCookies
Get all cookies. -
setCookies
Bulk-set cookies — convenience over repeatedcookie(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
Get window dimensions and position. -
setDimensions
Set window dimensions and/or position. -
activate
void activate()Activate the browser window (bring to front). -
pdf
Generate a PDF of the current page.- Specified by:
pdfin interfaceCoreDriver- 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:
mousein interfaceCoreDriver- Returns:
- a new Mouse object at position (0, 0)
-
mouse
Get a Mouse object positioned at an element's center. -
mouse
Get a Mouse object at specified coordinates. -
keys
Keys keys()Get a Keys object for keyboard input.- Specified by:
keysin interfaceCoreDriver- Returns:
- the Keys object for typing and key events
-
getPages
Get list of all page targets (tabs). -
switchPage
Switch to a page by title or URL substring. -
switchPage
void switchPage(int index) Switch to a page by index. -
switchPageById
Switch to a page by its backend target ID.Useful in conjunction with
drainOpenedTargets()— the drained entries carry atargetIdwhich 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
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, andtitle. Returns an empty list if nothing new was opened.Use case: an automation that clicks a link with
target="_blank"or a button that callswindow.open()can call this after the click to learn whether (and where) a new tab appeared, and then callswitchPage(String)orswitchPage(int)to focus it.Mirrors the
getDialog()pattern — the driver pushes events into an internal queue and the caller drains it, avoiding pollingTarget.getTargetsafter every action.Default implementation returns an empty list for drivers that don't track target events.
-
rightOf
Create a finder for elements to the right of the reference element. This is a convenience method that creates a Finder. -
leftOf
Create a finder for elements to the left of the reference element. This is a convenience method that creates a Finder. -
above
Create a finder for elements above the reference element. This is a convenience method that creates a Finder. -
below
Create a finder for elements below the reference element. This is a convenience method that creates a Finder. -
near
Create a finder for elements near the reference element. This is a convenience method that creates a Finder. -
timeout
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
Sleep for the given milliseconds. Returns the driver for chaining (v1 parity, e.g.delay(500).click(...)). -
intercept
Enable request interception with a handler.- Specified by:
interceptin interfaceCoreDriver- Parameters:
patterns- URL patterns to intercept (e.g., "*api/*")handler- the intercept handler (return InterceptResponse to mock, null to continue)
-
intercept
Enable request interception for all requests. -
stopIntercept
void stopIntercept()Stop request interception. -
quit
void quit()Close driver and browser.- Specified by:
quitin interfaceCoreDriver
-
close
void close()Alias for quit(). -
isTerminated
boolean isTerminated()Check if driver is terminated.- Specified by:
isTerminatedin interfaceCoreDriver
-
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
PooledDriverProviderto 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.PooledDriverProviderafter 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:
getOptionsin interfaceCoreDriver
-