Class CdpDriver
- All Implemented Interfaces:
CoreDriver,Driver,io.karatelabs.js.ObjectLike,io.karatelabs.js.SimpleObject
-
Field Summary
Fields inherited from interface io.karatelabs.js.SimpleObject
TO_STRING -
Method Summary
Modifier and TypeMethodDescriptionCreate a finder for elements above the reference element.voidactivate()Activate the browser window (bring to front).voidaddCdpEventListener(CdpEventListener listener) Add an external event listener that receives all CDP events.Get an attribute of an element.voidback()Navigate back in history.Create a finder for elements below the reference element.Clear an input element.voidClear all cookies.Click an element.voidclose()Close the current tab/page.static voidcloseAll()Close all active drivers.static CdpDriverConnect to an existing browser via WebSocket URL.static CdpDriverconnect(String webSocketUrl, CdpDriverOptions options) Connect to an existing browser with options.Get a cookie by name.voidSet a cookie.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 the queue of page targets (tabs) opened since the last call.booleanCheck if an element is enabled.booleanCheck if an element exists.Focus an element.voidforward()Navigate forward in history.voidMake the browser window fullscreen.Get the CDP-specific options.Get all cookies.Get the current frame, 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.Highlight an element.Get the outer HTML of an element.Input text into an element using CDP keypresses.voidintercept(InterceptHandler handler) Enable request interception for all requests.voidintercept(List<String> patterns, InterceptHandler handler) Enable request interception with a handler.booleanBounded liveness probe forreset.invalid reference
PooledDriverProviderbooleanCheck if driver is terminated.keys()Get a Keys object for keyboard input.Create a finder for elements to the left of the reference element.Find an element by locator.Find all elements matching a locator.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.Create a finder for elements near the reference element.voidonDialog(DialogHandler handler) Register a handler for JavaScript dialogs (alert, confirm, prompt, beforeunload).Find 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.Get a property of an element.voidquit()Close driver and browser.voidrefresh()Refresh the current page.voidreload()Reload the page ignoring cache.voidremoveCdpEventListener(CdpEventListener listener) Remove an external event listener.Create 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.Execute JavaScript and return result.Execute a script on an element.Execute a script on all matching elements.Scroll an element into view.Select an option from a dropdown by index.Select an option from a dropdown by text or value.voidsetDimensions(Map<String, Object> dimensions) Set window dimensions and/or position.voidNavigate to URL and wait for page load.static CdpDriverstart()Launch a new browser with default options.static CdpDriverstart(CdpDriverOptions options) Launch a new browser and create driver.static CdpDriverLaunch a headless browser.voidStop request interception.voidswitchFrame(int index) Switch to an iframe by index in the frame tree.voidswitchFrame(String locator) Switch to an iframe by locator (CSS, XPath, or wildcard).voidswitchPage(int index) Switch to a page by index.voidswitchPage(String titleOrUrl) Switch to a page by title or URL substring.voidswitchPageById(String targetId) Switch to a page by its backend target ID (unambiguous — avoids URL/title collisions thatswitchPage(String)is vulnerable to).Get the text content of an element.Get the value of an input element.Set the value of an input element.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, 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.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.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface io.karatelabs.driver.Driver
eval, eval, frame, jsGet, navigate, putMember, script, submit, tab, waitIfSubmitRequested, windowMethods inherited from interface io.karatelabs.js.ObjectLike
getPrototypeMethods inherited from interface io.karatelabs.js.SimpleObject
getMember, jsKeys, jsToString, removeMember, toMap
-
Method Details
-
addCdpEventListener
Add an external event listener that receives all CDP events. Used for traffic recording, debugging, etc.- Parameters:
listener- The listener to add
-
removeCdpEventListener
Remove an external event listener.- Parameters:
listener- The listener to remove
-
start
Launch a new browser and create driver. -
start
Launch a new browser with default options. -
startHeadless
Launch a headless browser. -
connect
Connect to an existing browser via WebSocket URL. -
connect
Connect to an existing browser with options. -
closeAll
public static void closeAll()Close all active drivers. -
setUrl
Navigate to URL and wait for page load. -
waitForPageLoad
Wait for page to load based on strategy.- Specified by:
waitForPageLoadin interfaceDriver
-
waitForPageLoad
Wait for page to load with custom timeout.- Specified by:
waitForPageLoadin interfaceDriver
-
getUrl
Get current URL. -
getTitle
Get page title. -
script
Execute JavaScript and return result. -
screenshot
public byte[] screenshot()Take screenshot and return PNG bytes.- Specified by:
screenshotin interfaceCoreDriver- Specified by:
screenshotin interfaceDriver- Returns:
- PNG image bytes
-
screenshot
public byte[] screenshot(boolean embed) Take screenshot, optionally embed in report.- Specified by:
screenshotin interfaceDriver
-
onDialog
Register a handler for JavaScript dialogs (alert, confirm, prompt, beforeunload). When a dialog opens, the handler is called with a Dialog object. The handler should call dialog.accept() or dialog.dismiss() to resolve the dialog. -
getDialogText
Get the current dialog message.- Specified by:
getDialogTextin interfaceDriver- Returns:
- the dialog message, or null if no dialog is open
-
getDialog
Get the current dialog if one is open. This is useful for detecting dialogs that appear after actions (e.g., click). The dialog remains available until handled via dialog() or the Dialog methods. -
dialog
public void dialog(boolean accept) Accept or dismiss the current dialog. This is used when no DialogHandler is registered. -
dialog
Accept or dismiss the current dialog with optional prompt input. This is used when no DialogHandler is registered.- Specified by:
dialogin interfaceCoreDriver- Specified by:
dialogin interfaceDriver- Parameters:
accept- true to accept (OK), false to dismiss (Cancel)input- the text to enter for prompt dialogs (ignored if accept is false)
-
switchFrame
public void switchFrame(int index) Switch to an iframe by index in the frame tree.- Specified by:
switchFramein interfaceDriver- Parameters:
index- the zero-based index of the frame
-
switchFrame
Switch to an iframe by locator (CSS, XPath, or wildcard). Pass null to switch back to the main frame.- Specified by:
switchFramein interfaceDriver- Parameters:
locator- the locator for the iframe element, or null to return to main frame
-
getCurrentFrame
Get the current frame, or null if in main frame.- Specified by:
getCurrentFramein interfaceDriver- Returns:
- the current frame info, or null
-
quit
public void quit()Close driver and browser.- Specified by:
quitin interfaceCoreDriver- Specified by:
quitin interfaceDriver
-
close
public void close()Close the current tab/page. After closing, automatically switches to another open tab if available. If this is the last tab, creates a blank page first to keep the browser alive. DESIGN NOTE: We must switch to another tab BEFORE closing the current one. When connected via page-specific WebSocket URL (e.g., /devtools/page/xxx), closing that page also closes the WebSocket connection. By switching first, we establish a new session on a different target, then safely close the old one. -
isTerminated
public boolean isTerminated()Description copied from interface:DriverCheck if driver is terminated.- Specified by:
isTerminatedin interfaceCoreDriver- Specified by:
isTerminatedin interfaceDriver
-
isResponsive
public boolean isResponsive()Bounded liveness probe forreset.invalid reference
PooledDriverProviderSends a trivial
Runtime.evaluate("1")with a 3-second CDP timeout (vs the default 30s). Returns false on any error, timeout, or closed socket — the caller treats false as "discard this driver, create a fresh one for the next scenario."Why this exists (context for future maintainers): observed in CI as deterministic "CDP timeout for: Page.navigate" failures in cookie.feature and keys.feature (same scenarios every run, alternating cookie pattern — classic "poisoned pool driver" signature). Every failing run was preceded by tab-switch.feature, which makes 5 activateTarget / Target.attachToTarget calls back-to-back. Each attach creates a new session on the driver's websocket and old sessions are never detached — the accumulated session state appears to leave Chrome unable to respond to Page.navigate on that specific driver, while the other pool driver stays healthy. Without this probe the broken driver kept getting handed back out and every other cookie scenario timed out at 30s.
We probe Runtime.evaluate rather than Page.navigate because it's cheap and local (no network). If even that is stuck, the driver is definitively done.
- Specified by:
isResponsivein interfaceDriver
-
getCdpClient
-
getOptions
Description copied from interface:DriverGet driver options.- Specified by:
getOptionsin interfaceCoreDriver- Specified by:
getOptionsin interfaceDriver
-
getCdpOptions
Get the CDP-specific options. -
click
Click an element. -
focus
Focus an element. -
clear
Clear an input element. -
input
Input text into an element using CDP keypresses. For time/date inputs that don't respond to CDP keystrokes, uses JS value assignment. -
value
Set the value of an input element. -
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. -
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. -
locate
Find an element by locator. -
locateAll
Find all elements matching a locator. -
optional
Find an element that may not exist (optional). -
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. -
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.- Specified by:
waitForAnyin interfaceDriver
-
waitForAny
Wait for any of the locators to match.- Specified by:
waitForAnyin interfaceDriver
-
waitForAny
Wait for any of the locators to match with custom timeout.- Specified by:
waitForAnyin interfaceDriver
-
waitForText
Wait for an element to contain specific text.- Specified by:
waitForTextin interfaceDriver
-
waitForText
Wait for an element to contain specific text with custom timeout.- Specified by:
waitForTextin interfaceDriver
-
waitForEnabled
Wait for an element to be enabled.- Specified by:
waitForEnabledin interfaceDriver
-
waitForEnabled
Wait for an element to be enabled with custom timeout.- Specified by:
waitForEnabledin interfaceDriver
-
waitForUrl
Wait for URL to contain expected string.- Specified by:
waitForUrlin interfaceDriver
-
waitForUrl
Wait for URL to contain expected string with custom timeout.- Specified by:
waitForUrlin interfaceDriver
-
waitUntil
Wait until a JavaScript expression on an element evaluates to truthy. The element is available as '_' in the expression. -
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.- Specified by:
waitForResultCountin interfaceDriver
-
waitForResultCount
Wait for a specific number of elements to match with custom timeout.- Specified by:
waitForResultCountin interfaceDriver
-
cookie
Get a cookie by name.- Specified by:
cookiein interfaceCoreDriver- Specified by:
cookiein interfaceDriver- Parameters:
name- the cookie name- Returns:
- the cookie as a Map, or null if not found
-
cookie
Set a cookie.- Specified by:
cookiein interfaceCoreDriver- Specified by:
cookiein interfaceDriver- Parameters:
cookie- the cookie as a Map with keys: name, value, domain, path, secure, httpOnly, sameSite, expires
-
deleteCookie
Delete a cookie by name.- Specified by:
deleteCookiein interfaceDriver- Parameters:
name- the cookie name
-
clearCookies
public void clearCookies()Clear all cookies.- Specified by:
clearCookiesin interfaceDriver
-
getCookies
Get all cookies.- Specified by:
getCookiesin interfaceDriver- Returns:
- list of cookies as Maps
-
maximize
public void maximize()Maximize the browser window. -
minimize
public void minimize()Minimize the browser window. -
fullscreen
public void fullscreen()Make the browser window fullscreen.- Specified by:
fullscreenin interfaceDriver
-
getDimensions
Get window dimensions and position.- Specified by:
getDimensionsin interfaceDriver- Returns:
- Map with keys: x, y, width, height, windowState
-
setDimensions
Set window dimensions and/or position.- Specified by:
setDimensionsin interfaceDriver- Parameters:
dimensions- Map with optional keys: x, y, width, height, windowState
-
pdf
Generate a PDF of the current page.- Specified by:
pdfin interfaceCoreDriver- Specified by:
pdfin interfaceDriver- Parameters:
options- Map with optional keys: scale, displayHeaderFooter, headerTemplate, footerTemplate, printBackground, landscape, pageRanges, paperWidth, paperHeight, marginTop, marginBottom, marginLeft, marginRight- Returns:
- PDF bytes
-
pdf
public byte[] pdf()Generate a PDF of the current page with default options. -
refresh
public void refresh()Refresh the current page. -
reload
public void reload()Reload the page ignoring cache. -
back
public void back()Navigate back in history. -
forward
public void forward()Navigate forward in history. -
activate
public void activate()Activate the browser window (bring to front). -
mouse
Get a Mouse object at position (0, 0).- Specified by:
mousein interfaceCoreDriver- Specified by:
mousein interfaceDriver- Returns:
- a new Mouse object
-
mouse
Get a Mouse object positioned at an element's center. -
mouse
Get a Mouse object at specified coordinates. -
keys
Get a Keys object for keyboard input. Returns the same instance to maintain modifier state (e.g., holding Shift across multiple calls).- Specified by:
keysin interfaceCoreDriver- Specified by:
keysin interfaceDriver- Returns:
- the Keys object for this driver
-
getPages
Get list of all page targets (tabs). Uses browserMethod() because Target.getTargets is a browser-level command. -
switchPage
Switch to a page by title or URL substring. Includes verification that the switch was successful.- Specified by:
switchPagein interfaceDriver- Parameters:
titleOrUrl- the title or URL substring to match
-
switchPageById
Switch to a page by its backend target ID (unambiguous — avoids URL/title collisions thatswitchPage(String)is vulnerable to).- Specified by:
switchPageByIdin interfaceDriver
-
drainOpenedTargets
Drain the queue of page targets (tabs) opened since the last call. Event-driven — no CDP round-trip. SeeDriver.drainOpenedTargets().- Specified by:
drainOpenedTargetsin interfaceDriver
-
switchPage
public void switchPage(int index) Switch to a page by index.- Specified by:
switchPagein interfaceDriver- Parameters:
index- the zero-based index
-
rightOf
Create a finder for elements to the right of the reference element. -
leftOf
Create a finder for elements to the left of the reference element. -
above
Create a finder for elements above the reference element. -
below
Create a finder for elements below the reference element. -
near
Create a finder for elements near the reference element. -
intercept
Enable request interception with a handler. The handler is called for each matching request. Return an InterceptResponse to mock, or null to continue to the network.- Specified by:
interceptin interfaceCoreDriver- Specified by:
interceptin interfaceDriver- Parameters:
patterns- URL patterns to intercept (e.g., "*api/*", "https://example.com/*")handler- the intercept handler
-
intercept
Enable request interception for all requests. -
stopIntercept
public void stopIntercept()Stop request interception.- Specified by:
stopInterceptin interfaceDriver
-