Class HtmlUnitDriver
- All Implemented Interfaces:
org.openqa.selenium.HasCapabilities,org.openqa.selenium.interactions.Interactive,org.openqa.selenium.JavascriptExecutor,org.openqa.selenium.SearchContext,org.openqa.selenium.WebDriver
WebDriver that drives
HtmlUnit, which is a headless
(GUI-less) browser simulator.
The main supported browsers are Chrome, Edge, Firefox and Internet Explorer.
- Author:
- Alexei Barantsev, Ahmed Ashour, Rafael Jimenez, Luke Inman-Semerau, Kay McCormick, Simon Stewart, Javier Neira, Ronald Brill, Rob Winch, Andrei Solntsev, Martin Bartoš, Scott Babcock
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static classMaintains a bidirectional mapping betweenDomElementinstances and their correspondingHtmlUnitWebElementwrappers.protected classImplementation ofWebDriver.OptionsforHtmlUnitDriver.protected static interfaceRepresents a JavaScript array-like result set returned from script execution.Nested classes/interfaces inherited from interface org.openqa.selenium.WebDriver
org.openqa.selenium.WebDriver.Navigation, org.openqa.selenium.WebDriver.Options, org.openqa.selenium.WebDriver.TargetLocator, org.openqa.selenium.WebDriver.Timeouts, org.openqa.selenium.WebDriver.Window -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionConstructs a new instance with JavaScript disabled, and thedefaultBrowserVersion.HtmlUnitDriver(boolean enableJavascript) Constructs a new instance, specify JavaScript support and using thedefaultBrowserVersion.HtmlUnitDriver(BrowserVersion version) Constructs a new instance with the specifiedBrowserVersion.HtmlUnitDriver(BrowserVersion version, boolean enableJavascript) Constructs a new instance with the specifiedBrowserVersionand the JavaScript support.HtmlUnitDriver(org.openqa.selenium.Capabilities capabilities) The browserName isBrowser.HTMLUNIT"htmlunit" and the browserVersion denotes the required browser AND its version.HtmlUnitDriver(org.openqa.selenium.Capabilities desiredCapabilities, org.openqa.selenium.Capabilities requiredCapabilities) Constructs a new instance with the specified desired and requiredCapabilities. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidassertElementNotStale(DomElement element) Verifies that the providedDomElementis still attached to the current page and therefore safe for user interaction.voidclick(DomElement element, boolean directClick) Performs a click operation on the specified element.voidclose()voiddoubleClick(DomElement element) Performs a double click on the specified element.executeAsyncScript(String script, Object... args) executeScript(String script, Object... args) org.openqa.selenium.WebElementfindElement(org.openqa.selenium.By by) org.openqa.selenium.WebElementfindElement(HtmlUnitWebElement element, org.openqa.selenium.By by) Locates a singleWebElementusing the given search context and selector.List<org.openqa.selenium.WebElement>findElements(org.openqa.selenium.By by) List<org.openqa.selenium.WebElement>findElements(HtmlUnitWebElement element, org.openqa.selenium.By by) Locates allWebElements matching the given selector within the provided search context.voidprotected voidAllows HtmlUnit's about:blank to be loaded in the constructor, and may be useful for other tests?getAlert()Returns the currentHtmlUnitAlertassociated with this context.Get the simulatedBrowserVersion.org.openqa.selenium.CapabilitiesReturns the currentHtmlUnitWindowused by this driver.Returns theHtmlUnitDriver.ElementsMapthat tracks elements known to this context.Returns the driver's keyboard implementation.getMouse()Returns the driver's mouse implementation.getTitle()Returns the underlyingWebClientused by this driver.protected <X> XimplicitlyWaitFor(Callable<X> condition) Executes the given condition using Selenium-style implicit wait semantics.booleanIndicates whether insecure SSL/TLS certificates are accepted.booleanIndicates whether automatic image downloading is enabled.booleanIndicates whether JavaScript execution is enabled in the underlyingWebClient.org.openqa.selenium.WebDriver.Optionsmanage()protected WebClientmodifyWebClient(WebClient client) Child classes can override this method to customize the WebClient that the HtmlUnit driver uses.voidmouseDown(DomElement element) Presses the primary mouse button over the specified element.voidmouseMove(DomElement element) Moves the virtual mouse cursor to the specified element.voidmouseUp(DomElement element) Releases the pressed mouse button over the specified element.org.openqa.selenium.WebDriver.Navigationnavigate()protected WebClientnewWebClient(BrowserVersion version) Create the underlying WebClient, but don't set any fields on it.voidOpens a new, blank browser window and sets it as the driver's current window.voidperform(Collection<org.openqa.selenium.interactions.Sequence> sequences) voidquit()voidprotected voidExecutes the given task asynchronously on the driver's internal executor, optionally blocking the calling thread until completion depending on the configuredHtmlUnitDriver.PageLoadStrategy.voidsendKeys(HtmlUnitWebElement element, CharSequence... value) Sends keystrokes to the specified element.voidsetAcceptInsecureCerts(boolean accept) Configures whether the driver should accept insecure SSL/TLS certificates.voidsetAutoProxy(String autoProxyUrl) Sets Proxy Autoconfiguration URL for WebClient.voidsetCurrentWindow(WebWindow window) Sets the currentWebWindowfor this context.voidsetDownloadImages(boolean downloadImages) Enables or disables automatic image downloading.voidsetExecutor(Executor executor) Sets theExecutorto be used for submitting async tasks to.voidsetHTTPProxy(String host, int port, List<String> noProxyHosts) Sets HTTP proxy for WebClient with bypass proxy hosts.voidsetJavascriptEnabled(boolean enableJavascript) Enables or disables JavaScript execution in the underlyingWebClient.voidSets HTTP proxy for WebClient.voidsetProxySettings(org.openqa.selenium.Proxy proxy) Set proxy for WebClient using Proxy.voidsetSocksProxy(String host, int port) Sets SOCKS proxy for WebClient.voidsetSocksProxy(String host, int port, List<String> noProxyHosts) Sets SOCKS proxy for WebClient with bypass proxy hosts.voidsubmit(HtmlUnitWebElement element) Submits a form associated with the specified element.org.openqa.selenium.WebDriver.TargetLocatorswitchTo()protected voidSwitches the driver's context to the default content of the specified window.toWebElement(String elementId) Retrieves an existingHtmlUnitWebElementby its element ID.protected HtmlUnitWebElementtoWebElement(DomElement element) Wraps the givenDomElementinto a correspondingHtmlUnitWebElement, creating and caching the wrapper if it does not already exist.Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.openqa.selenium.JavascriptExecutor
executeScript, getPinnedScripts, pin, unpin
-
Field Details
-
BROWSER_LANGUAGE_CAPABILITY
BROWSER_LANGUAGE_CAPABILITY = "browserLanguage".- See Also:
-
DOWNLOAD_IMAGES_CAPABILITY
DOWNLOAD_IMAGES_CAPABILITY = "downloadImages".- See Also:
-
JAVASCRIPT_ENABLED
JAVASCRIPT_ENABLED = "javascriptEnabled".- See Also:
-
-
Constructor Details
-
HtmlUnitDriver
public HtmlUnitDriver()Constructs a new instance with JavaScript disabled, and thedefaultBrowserVersion. -
HtmlUnitDriver
Constructs a new instance with the specifiedBrowserVersion.- Parameters:
version- the browser version to use
-
HtmlUnitDriver
public HtmlUnitDriver(boolean enableJavascript) Constructs a new instance, specify JavaScript support and using thedefaultBrowserVersion.- Parameters:
enableJavascript- whether to enable JavaScript support or not
-
HtmlUnitDriver
Constructs a new instance with the specifiedBrowserVersionand the JavaScript support.- Parameters:
version- the browser version to useenableJavascript- whether to enable JavaScript support or not
-
HtmlUnitDriver
public HtmlUnitDriver(org.openqa.selenium.Capabilities desiredCapabilities, org.openqa.selenium.Capabilities requiredCapabilities) Constructs a new instance with the specified desired and requiredCapabilities.- Parameters:
desiredCapabilities- desired capabilitiesrequiredCapabilities- required capabilities
-
HtmlUnitDriver
public HtmlUnitDriver(org.openqa.selenium.Capabilities capabilities) The browserName isBrowser.HTMLUNIT"htmlunit" and the browserVersion denotes the required browser AND its version. For example "chrome" for Chrome, "firefox-100" for Firefox 100.- Parameters:
capabilities- desired capabilities requested for the htmlunit driver session
-
-
Method Details
-
runAsync
Executes the given task asynchronously on the driver's internal executor, optionally blocking the calling thread until completion depending on the configuredHtmlUnitDriver.PageLoadStrategy.This method provides a unified mechanism for running mouse, keyboard, and element operations in a background thread while preserving WebDriver's synchronous execution semantics when required. The behavior differs based on the configured page load strategy:
PageLoadStrategy.NONE— the task is dispatched asynchronously and this method returns immediately.- Any other strategy — the calling thread waits until the task completes. The method blocks using an internal condition variable until the executed runnable signals completion.
Only one synchronous operation (i.e., one operation requiring waiting) may run at a time. If another such operation is already executing, the calling thread waits until the previous task finishes.
Any
RuntimeExceptionthrown by the task is captured and re-thrown on the calling thread after the task completes, preserving WebDriver-consistent error reporting.- Parameters:
r- the runnable task to execute; must not benull- Throws:
RuntimeException- if the task throws a runtime exception during execution
-
click
Performs a click operation on the specified element.This simulates a WebDriver pointer click by firing
mousedown,mouseup, andclickevents on the target element. The action is executed asynchronously.- Parameters:
element- the DOM element to receive the clickdirectClick- iftrue, the click is dispatched directly without moving the mouse cursor; iffalse, a hover/move sequence may be performed before the click depending on HtmlUnit’s behavior
-
doubleClick
Performs a double click on the specified element.This simulates a WebDriver double-click gesture by issuing two click sequences in rapid succession and dispatching a
dblclickevent. The action is executed asynchronously.- Parameters:
element- the DOM element to double-click
-
mouseUp
Releases the pressed mouse button over the specified element.This simulates a WebDriver
pointerUpaction and fires amouseupevent on the element. The action is executed asynchronously.- Parameters:
element- the DOM element on which to release the mouse button
-
mouseMove
Moves the virtual mouse cursor to the specified element.This simulates a WebDriver
pointerMoveaction. Moving the cursor may triggermouseover,mouseenter, andmousemoveevents as appropriate. The action is executed asynchronously.- Parameters:
element- the DOM element to move the mouse to
-
mouseDown
Presses the primary mouse button over the specified element.This simulates a WebDriver
pointerDownaction and fires amousedownevent. The action is executed asynchronously.- Parameters:
element- the DOM element on which to press the mouse button
-
submit
Submits a form associated with the specified element.This behaves like WebDriver's form submission semantics: if the element is a form, it is submitted directly; if it is a control inside a form, the containing form is submitted. HTML5 form submission validation rules apply. The action is executed asynchronously.
- Parameters:
element- the HtmlUnitWebElement whose form should be submitted
-
sendKeys
Sends keystrokes to the specified element.This simulates WebDriver keyboard input, including dispatch of
keydown,keypress, andkeyupevents as appropriate. Characters are inserted into the element based on standard DOM editing rules. The action is executed asynchronously.- Parameters:
element- the element to receive keyboard inputvalue- one or more sequences of characters to send
-
getBrowserVersion
Get the simulatedBrowserVersion.- Returns:
- the used
BrowserVersion
-
newWebClient
Create the underlying WebClient, but don't set any fields on it.- Parameters:
version- Which browser to emulate- Returns:
- a new instance of WebClient.
-
modifyWebClient
Child classes can override this method to customize the WebClient that the HtmlUnit driver uses.- Parameters:
client- The client to modify- Returns:
- The modified client
-
getAlert
Returns the currentHtmlUnitAlertassociated with this context.- Returns:
- the active alert instance, or
nullif no alert is present
-
getElementsMap
Returns theHtmlUnitDriver.ElementsMapthat tracks elements known to this context. This map typically provides lookup and indexing for DOM or component references.- Returns:
- the elements map, never
null
-
setCurrentWindow
Sets the currentWebWindowfor this context. If the provided window differs from the currently tracked one, a newHtmlUnitWindowwrapper is created and stored.- Parameters:
window- the WebWindow that should become the current window; must not benull
-
setProxySettings
public void setProxySettings(org.openqa.selenium.Proxy proxy) Set proxy for WebClient using Proxy.- Parameters:
proxy- The proxy preferences.
-
setProxy
Sets HTTP proxy for WebClient.- Parameters:
host- The hostname of HTTP proxyport- The port of HTTP proxy, 0 means HTTP proxy w/o port
-
setHTTPProxy
Sets HTTP proxy for WebClient with bypass proxy hosts.- Parameters:
host- The hostname of HTTP proxyport- The port of HTTP proxy, 0 means HTTP proxy w/o portnoProxyHosts- The list of hosts which need to bypass HTTP proxy
-
setSocksProxy
Sets SOCKS proxy for WebClient.- Parameters:
host- The hostname of SOCKS proxyport- The port of SOCKS proxy, 0 means HTTP proxy w/o port
-
setSocksProxy
Sets SOCKS proxy for WebClient with bypass proxy hosts.- Parameters:
host- The hostname of SOCKS proxyport- The port of SOCKS proxy, 0 means HTTP proxy w/o portnoProxyHosts- The list of hosts which need to bypass SOCKS proxy
-
setExecutor
Sets theExecutorto be used for submitting async tasks to. You have to close this manually onquit()- Parameters:
executor- theExecutorto use
-
setAutoProxy
Sets Proxy Autoconfiguration URL for WebClient.- Parameters:
autoProxyUrl- The Proxy Autoconfiguration URL
-
getCapabilities
public org.openqa.selenium.Capabilities getCapabilities()- Specified by:
getCapabilitiesin interfaceorg.openqa.selenium.HasCapabilities
-
get
- Specified by:
getin interfaceorg.openqa.selenium.WebDriver
-
get
Allows HtmlUnit's about:blank to be loaded in the constructor, and may be useful for other tests?- Parameters:
fullUrl- The URL to visit
-
getCurrentUrl
- Specified by:
getCurrentUrlin interfaceorg.openqa.selenium.WebDriver
-
getTitle
- Specified by:
getTitlein interfaceorg.openqa.selenium.WebDriver
-
findElement
public org.openqa.selenium.WebElement findElement(org.openqa.selenium.By by) - Specified by:
findElementin interfaceorg.openqa.selenium.SearchContext- Specified by:
findElementin interfaceorg.openqa.selenium.WebDriver
-
findElements
- Specified by:
findElementsin interfaceorg.openqa.selenium.SearchContext- Specified by:
findElementsin interfaceorg.openqa.selenium.WebDriver
-
findElement
public org.openqa.selenium.WebElement findElement(HtmlUnitWebElement element, org.openqa.selenium.By by) Locates a singleWebElementusing the given search context and selector.This method applies the configured implicit wait timeout: if the element is not immediately available, the lookup is repeatedly retried until it is found or the timeout expires.
- Parameters:
element- the search context, typically the parentHtmlUnitWebElementby- the locating mechanism to use- Returns:
- the located WebElement
- Throws:
org.openqa.selenium.NoSuchElementException- if the element cannot be found within the implicit wait
-
findElements
public List<org.openqa.selenium.WebElement> findElements(HtmlUnitWebElement element, org.openqa.selenium.By by) Locates allWebElements matching the given selector within the provided search context.If the configured implicit wait timeout exceeds the driver's polling interval, the method repeatedly searches until at least one element is found or the timeout expires. If the timeout is shorter than the polling interval, the search is performed only once.
- Parameters:
element- the search context, typically anHtmlUnitWebElementby- the locating strategy- Returns:
- a list of all matching elements; may be empty if none are found before timeout
-
getPageSource
- Specified by:
getPageSourcein interfaceorg.openqa.selenium.WebDriver
-
close
public void close()- Specified by:
closein interfaceorg.openqa.selenium.WebDriver
-
quit
public void quit()- Specified by:
quitin interfaceorg.openqa.selenium.WebDriver
-
getWindowHandles
- Specified by:
getWindowHandlesin interfaceorg.openqa.selenium.WebDriver
-
getWindowHandle
- Specified by:
getWindowHandlein interfaceorg.openqa.selenium.WebDriver
-
executeScript
- Specified by:
executeScriptin interfaceorg.openqa.selenium.JavascriptExecutor
-
executeAsyncScript
- Specified by:
executeAsyncScriptin interfaceorg.openqa.selenium.JavascriptExecutor
-
assertElementNotStale
Verifies that the providedDomElementis still attached to the current page and therefore safe for user interaction.This check mirrors Selenium's
StaleElementReferenceExceptionbehavior. An element is considered stale if:- the element belongs to a different page than the driver's current window, or
- the element is no longer part of the DOM tree (i.e., it has no ancestor
that is an
SgmlPage).
If either condition is detected, a
StaleElementReferenceExceptionis thrown, indicating that the element cannot be interacted with.- Parameters:
element- the element to validate; must not benull- Throws:
org.openqa.selenium.StaleElementReferenceException- if the element is detached, removed, or belongs to a different page
-
getKeyboard
Returns the driver's keyboard implementation.This object is used to simulate keyboard input, including sending keys to elements and generating key press/release events.
- Returns:
- the
HtmlUnitKeyboardassociated with this driver
-
getMouse
Returns the driver's mouse implementation.The returned object supports pointer-based interactions such as clicking, moving the pointer, and pressing or releasing mouse buttons.
- Returns:
- the
HtmlUnitMouseassociated with this driver
-
switchTo
public org.openqa.selenium.WebDriver.TargetLocator switchTo()- Specified by:
switchToin interfaceorg.openqa.selenium.WebDriver
-
toWebElement
Wraps the givenDomElementinto a correspondingHtmlUnitWebElement, creating and caching the wrapper if it does not already exist.- Parameters:
element- the DOM element to wrap; must not benull- Returns:
- the associated
HtmlUnitWebElement, nevernull
-
toWebElement
Retrieves an existingHtmlUnitWebElementby its element ID.This method does not search the DOM; it only returns an element previously known and mapped by
HtmlUnitDriver.ElementsMap.- Parameters:
elementId- the unique ID of the element to retrieve- Returns:
- the corresponding
HtmlUnitWebElement, ornullif it is not mapped
-
isJavascriptEnabled
public boolean isJavascriptEnabled()Indicates whether JavaScript execution is enabled in the underlyingWebClient.- Returns:
trueif JavaScript is enabled,falseotherwise
-
setJavascriptEnabled
public void setJavascriptEnabled(boolean enableJavascript) Enables or disables JavaScript execution in the underlyingWebClient.- Parameters:
enableJavascript-trueto enable JavaScript,falseto disable it
-
isDownloadImages
public boolean isDownloadImages()Indicates whether automatic image downloading is enabled.- Returns:
trueif images will be downloaded,falseotherwise
-
setDownloadImages
public void setDownloadImages(boolean downloadImages) Enables or disables automatic image downloading.- Parameters:
downloadImages-trueto download images,falseotherwise
-
setAcceptInsecureCerts
public void setAcceptInsecureCerts(boolean accept) Configures whether the driver should accept insecure SSL/TLS certificates.- Parameters:
accept-trueto allow insecure certificates,falseto reject them
-
isAcceptInsecureCerts
public boolean isAcceptInsecureCerts()Indicates whether insecure SSL/TLS certificates are accepted.- Returns:
trueif insecure certificates are allowed,falseotherwise
-
implicitlyWaitFor
Executes the given condition using Selenium-style implicit wait semantics.The method repeatedly invokes the provided
Callableuntil it either:- returns a non-
nullvalue, - returns
trueif the return type isBoolean, - or the implicit wait timeout expires.
If the implicit wait timeout is shorter than the configured sleep interval, the condition is evaluated only once.
- Type Parameters:
X- the return type of the condition- Parameters:
condition- the operation to evaluate until it succeeds or times out- Returns:
- the successful result of the condition, or
nullif it timed out - Throws:
org.openqa.selenium.WebDriverException- if the condition throws an exception that is not aRuntimeExceptionRuntimeException- if the last invocation of the condition throws one
- returns a non-
-
getWebClient
Returns the underlyingWebClientused by this driver.- Returns:
- the active
WebClient - Throws:
org.openqa.selenium.NoSuchSessionException- if the session has been closed
-
getCurrentWindow
Returns the currentHtmlUnitWindowused by this driver.- Returns:
- the active window
- Throws:
org.openqa.selenium.NoSuchSessionException- if the session has been closedorg.openqa.selenium.NoSuchWindowException- if the current window reference is invalid or the window is closed
-
manage
public org.openqa.selenium.WebDriver.Options manage()- Specified by:
managein interfaceorg.openqa.selenium.WebDriver
-
perform
- Specified by:
performin interfaceorg.openqa.selenium.interactions.Interactive
-
resetInputState
public void resetInputState()- Specified by:
resetInputStatein interfaceorg.openqa.selenium.interactions.Interactive
-
switchToDefaultContentOfWindow
Switches the driver's context to the default content of the specified window.This method inspects the provided
WebWindow, retrieves its enclosedPage, and—if that page is anHtmlPage—switches the current window to the page's enclosing top-level window.In effect, this resets the driver's frame context for the given window, analogous to Selenium's
switchTo().defaultContent().- Parameters:
window- theWebWindowwhose default content should become active; must not benull
-
openNewWindow
public void openNewWindow()Opens a new, blank browser window and sets it as the driver's current window.This method calls
webClient_.openWindow()usingabout:blankas the initial page, then updates the driver's internal window reference to point to the newly created window.Similar to Selenium's
driver.switchTo().newWindow(WindowType.WINDOW), but implemented using HtmlUnit's headless window model.
-