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

    public class HtmlUnitDriver
    extends Object
    implements org.openqa.selenium.WebDriver, org.openqa.selenium.JavascriptExecutor, org.openqa.selenium.HasCapabilities, org.openqa.selenium.interactions.Interactive
    An implementation of 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
    • Field Detail

      • BROWSER_LANGUAGE_CAPABILITY

        public static final String BROWSER_LANGUAGE_CAPABILITY
        BROWSER_LANGUAGE_CAPABILITY = "browserLanguage".
        See Also:
        Constant Field Values
      • DOWNLOAD_IMAGES_CAPABILITY

        public static final String DOWNLOAD_IMAGES_CAPABILITY
        DOWNLOAD_IMAGES_CAPABILITY = "downloadImages".
        See Also:
        Constant Field Values
      • JAVASCRIPT_ENABLED

        public static final String JAVASCRIPT_ENABLED
        JAVASCRIPT_ENABLED = "javascriptEnabled".
        See Also:
        Constant Field Values
    • Constructor Detail

      • HtmlUnitDriver

        public HtmlUnitDriver()
        Constructs a new instance with JavaScript disabled, and the default BrowserVersion.
      • HtmlUnitDriver

        public HtmlUnitDriver​(BrowserVersion version)
        Constructs a new instance with the specified BrowserVersion.
        Parameters:
        version - the browser version to use
      • HtmlUnitDriver

        public HtmlUnitDriver​(boolean enableJavascript)
        Constructs a new instance, specify JavaScript support and using the default BrowserVersion.
        Parameters:
        enableJavascript - whether to enable JavaScript support or not
      • HtmlUnitDriver

        public HtmlUnitDriver​(BrowserVersion version,
                              boolean enableJavascript)
        Constructs a new instance with the specified BrowserVersion and the JavaScript support.
        Parameters:
        version - the browser version to use
        enableJavascript - 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 required Capabilities.
        Parameters:
        desiredCapabilities - desired capabilities
        requiredCapabilities - required capabilities
      • HtmlUnitDriver

        public HtmlUnitDriver​(org.openqa.selenium.Capabilities capabilities)
        The browserName is Browser.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 Detail

      • runAsync

        protected void runAsync​(Runnable r)
        Executes the given task asynchronously on the driver's internal executor, optionally blocking the calling thread until completion depending on the configured HtmlUnitDriver.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 RuntimeException thrown 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 be null
        Throws:
        RuntimeException - if the task throws a runtime exception during execution
      • click

        public void click​(DomElement element,
                          boolean directClick)
        Performs a click operation on the specified element.

        This simulates a WebDriver pointer click by firing mousedown, mouseup, and click events on the target element. The action is executed asynchronously.

        Parameters:
        element - the DOM element to receive the click
        directClick - if true, the click is dispatched directly without moving the mouse cursor; if false, a hover/move sequence may be performed before the click depending on HtmlUnit’s behavior
      • doubleClick

        public void doubleClick​(DomElement element)
        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 dblclick event. The action is executed asynchronously.

        Parameters:
        element - the DOM element to double-click
      • mouseUp

        public void mouseUp​(DomElement element)
        Releases the pressed mouse button over the specified element.

        This simulates a WebDriver pointerUp action and fires a mouseup event on the element. The action is executed asynchronously.

        Parameters:
        element - the DOM element on which to release the mouse button
      • mouseMove

        public void mouseMove​(DomElement element)
        Moves the virtual mouse cursor to the specified element.

        This simulates a WebDriver pointerMove action. Moving the cursor may trigger mouseover, mouseenter, and mousemove events as appropriate. The action is executed asynchronously.

        Parameters:
        element - the DOM element to move the mouse to
      • mouseDown

        public void mouseDown​(DomElement element)
        Presses the primary mouse button over the specified element.

        This simulates a WebDriver pointerDown action and fires a mousedown event. The action is executed asynchronously.

        Parameters:
        element - the DOM element on which to press the mouse button
      • submit

        public void submit​(HtmlUnitWebElement element)
        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

        public void sendKeys​(HtmlUnitWebElement element,
                             CharSequence... value)
        Sends keystrokes to the specified element.

        This simulates WebDriver keyboard input, including dispatch of keydown, keypress, and keyup events 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 input
        value - one or more sequences of characters to send
      • getBrowserVersion

        public BrowserVersion getBrowserVersion()
        Get the simulated BrowserVersion.
        Returns:
        the used BrowserVersion
      • newWebClient

        protected WebClient newWebClient​(BrowserVersion version)
        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

        protected WebClient modifyWebClient​(WebClient client)
        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

        public HtmlUnitAlert getAlert()
        Returns the current HtmlUnitAlert associated with this context.
        Returns:
        the active alert instance, or null if no alert is present
      • getElementsMap

        public HtmlUnitDriver.ElementsMap getElementsMap()
        Returns the HtmlUnitDriver.ElementsMap that 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

        public void setCurrentWindow​(WebWindow window)
        Sets the current WebWindow for this context. If the provided window differs from the currently tracked one, a new HtmlUnitWindow wrapper is created and stored.
        Parameters:
        window - the WebWindow that should become the current window; must not be null
      • setProxySettings

        public void setProxySettings​(org.openqa.selenium.Proxy proxy)
        Set proxy for WebClient using Proxy.
        Parameters:
        proxy - The proxy preferences.
      • setProxy

        public void setProxy​(String host,
                             int port)
        Sets HTTP proxy for WebClient.
        Parameters:
        host - The hostname of HTTP proxy
        port - The port of HTTP proxy, 0 means HTTP proxy w/o port
      • setHTTPProxy

        public void setHTTPProxy​(String host,
                                 int port,
                                 List<String> noProxyHosts)
        Sets HTTP proxy for WebClient with bypass proxy hosts.
        Parameters:
        host - The hostname of HTTP proxy
        port - The port of HTTP proxy, 0 means HTTP proxy w/o port
        noProxyHosts - The list of hosts which need to bypass HTTP proxy
      • setSocksProxy

        public void setSocksProxy​(String host,
                                  int port)
        Sets SOCKS proxy for WebClient.
        Parameters:
        host - The hostname of SOCKS proxy
        port - The port of SOCKS proxy, 0 means HTTP proxy w/o port
      • setSocksProxy

        public void setSocksProxy​(String host,
                                  int port,
                                  List<String> noProxyHosts)
        Sets SOCKS proxy for WebClient with bypass proxy hosts.
        Parameters:
        host - The hostname of SOCKS proxy
        port - The port of SOCKS proxy, 0 means HTTP proxy w/o port
        noProxyHosts - The list of hosts which need to bypass SOCKS proxy
      • setExecutor

        public void setExecutor​(Executor executor)
        Sets the Executor to be used for submitting async tasks to. You have to close this manually on quit()
        Parameters:
        executor - the Executor to use
      • setAutoProxy

        public void setAutoProxy​(String autoProxyUrl)
        Sets Proxy Autoconfiguration URL for WebClient.
        Parameters:
        autoProxyUrl - The Proxy Autoconfiguration URL
      • getCapabilities

        public org.openqa.selenium.Capabilities getCapabilities()
        Specified by:
        getCapabilities in interface org.openqa.selenium.HasCapabilities
      • get

        public void get​(String url)
        Specified by:
        get in interface org.openqa.selenium.WebDriver
      • get

        protected void get​(URL fullUrl)
        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

        public String getCurrentUrl()
        Specified by:
        getCurrentUrl in interface org.openqa.selenium.WebDriver
      • getTitle

        public String getTitle()
        Specified by:
        getTitle in interface org.openqa.selenium.WebDriver
      • findElement

        public org.openqa.selenium.WebElement findElement​(org.openqa.selenium.By by)
        Specified by:
        findElement in interface org.openqa.selenium.SearchContext
        Specified by:
        findElement in interface org.openqa.selenium.WebDriver
      • findElements

        public List<org.openqa.selenium.WebElement> findElements​(org.openqa.selenium.By by)
        Specified by:
        findElements in interface org.openqa.selenium.SearchContext
        Specified by:
        findElements in interface org.openqa.selenium.WebDriver
      • findElement

        public org.openqa.selenium.WebElement findElement​(HtmlUnitWebElement element,
                                                          org.openqa.selenium.By by)
        Locates a single WebElement using 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 parent HtmlUnitWebElement
        by - 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 all WebElements 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 an HtmlUnitWebElement
        by - the locating strategy
        Returns:
        a list of all matching elements; may be empty if none are found before timeout
      • getPageSource

        public String getPageSource()
        Specified by:
        getPageSource in interface org.openqa.selenium.WebDriver
      • close

        public void close()
        Specified by:
        close in interface org.openqa.selenium.WebDriver
      • quit

        public void quit()
        Specified by:
        quit in interface org.openqa.selenium.WebDriver
      • getWindowHandles

        public Set<String> getWindowHandles()
        Specified by:
        getWindowHandles in interface org.openqa.selenium.WebDriver
      • getWindowHandle

        public String getWindowHandle()
        Specified by:
        getWindowHandle in interface org.openqa.selenium.WebDriver
      • executeScript

        public Object executeScript​(String script,
                                    Object... args)
        Specified by:
        executeScript in interface org.openqa.selenium.JavascriptExecutor
      • executeAsyncScript

        public Object executeAsyncScript​(String script,
                                         Object... args)
        Specified by:
        executeAsyncScript in interface org.openqa.selenium.JavascriptExecutor
      • assertElementNotStale

        protected void assertElementNotStale​(DomElement element)
        Verifies that the provided DomElement is still attached to the current page and therefore safe for user interaction.

        This check mirrors Selenium's StaleElementReferenceException behavior. 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 StaleElementReferenceException is thrown, indicating that the element cannot be interacted with.

        Parameters:
        element - the element to validate; must not be null
        Throws:
        org.openqa.selenium.StaleElementReferenceException - if the element is detached, removed, or belongs to a different page
      • getKeyboard

        public HtmlUnitKeyboard 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 HtmlUnitKeyboard associated with this driver
      • getMouse

        public HtmlUnitMouse 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 HtmlUnitMouse associated with this driver
      • switchTo

        public org.openqa.selenium.WebDriver.TargetLocator switchTo()
        Specified by:
        switchTo in interface org.openqa.selenium.WebDriver
      • navigate

        public org.openqa.selenium.WebDriver.Navigation navigate()
        Specified by:
        navigate in interface org.openqa.selenium.WebDriver
      • isJavascriptEnabled

        public boolean isJavascriptEnabled()
        Indicates whether JavaScript execution is enabled in the underlying WebClient.
        Returns:
        true if JavaScript is enabled, false otherwise
      • setJavascriptEnabled

        public void setJavascriptEnabled​(boolean enableJavascript)
        Enables or disables JavaScript execution in the underlying WebClient.
        Parameters:
        enableJavascript - true to enable JavaScript, false to disable it
      • isDownloadImages

        public boolean isDownloadImages()
        Indicates whether automatic image downloading is enabled.
        Returns:
        true if images will be downloaded, false otherwise
      • setDownloadImages

        public void setDownloadImages​(boolean downloadImages)
        Enables or disables automatic image downloading.
        Parameters:
        downloadImages - true to download images, false otherwise
      • setAcceptInsecureCerts

        public void setAcceptInsecureCerts​(boolean accept)
        Configures whether the driver should accept insecure SSL/TLS certificates.
        Parameters:
        accept - true to allow insecure certificates, false to reject them
      • isAcceptInsecureCerts

        public boolean isAcceptInsecureCerts()
        Indicates whether insecure SSL/TLS certificates are accepted.
        Returns:
        true if insecure certificates are allowed, false otherwise
      • implicitlyWaitFor

        protected <X> X implicitlyWaitFor​(Callable<X> condition)
        Executes the given condition using Selenium-style implicit wait semantics.

        The method repeatedly invokes the provided Callable until it either:

        • returns a non-null value,
        • returns true if the return type is Boolean,
        • 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 null if it timed out
        Throws:
        org.openqa.selenium.WebDriverException - if the condition throws an exception that is not a RuntimeException
        RuntimeException - if the last invocation of the condition throws one
      • getWebClient

        public WebClient getWebClient()
        Returns the underlying WebClient used by this driver.
        Returns:
        the active WebClient
        Throws:
        org.openqa.selenium.NoSuchSessionException - if the session has been closed
      • getCurrentWindow

        public HtmlUnitWindow getCurrentWindow()
        Returns the current HtmlUnitWindow used by this driver.
        Returns:
        the active window
        Throws:
        org.openqa.selenium.NoSuchSessionException - if the session has been closed
        org.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:
        manage in interface org.openqa.selenium.WebDriver
      • perform

        public void perform​(Collection<org.openqa.selenium.interactions.Sequence> sequences)
        Specified by:
        perform in interface org.openqa.selenium.interactions.Interactive
      • resetInputState

        public void resetInputState()
        Specified by:
        resetInputState in interface org.openqa.selenium.interactions.Interactive
      • switchToDefaultContentOfWindow

        protected void switchToDefaultContentOfWindow​(WebWindow window)
        Switches the driver's context to the default content of the specified window.

        This method inspects the provided WebWindow, retrieves its enclosed Page, and—if that page is an HtmlPage—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 - the WebWindow whose default content should become active; must not be null
      • openNewWindow

        public void openNewWindow()
        Opens a new, blank browser window and sets it as the driver's current window.

        This method calls webClient_.openWindow() using about:blank as 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.