HtmlUnitDriverOptions Class

December 8, 2024 · View on GitHub

The HtmlUnitDriverOptions class provides methods to manage options specific to HtmlUnitDriver. This browser-specific options object is assigned to the custom capability name garg:htmlunitOptions.

HtmlUnitDriverOptions example usage:

HtmlUnitDriverOptions options = new HtmlUnitDriverOptions()
    .setWebClientVersion(BrowserVersion.FIREFOX_ESR)
    .setJavaScriptEnabled(true);

// For use with HtmlUnitDriver:
HtmlUnitDriver driver = new HtmlUnitDriver(options);

// For use with RemoteWebDriver:
RemoteWebDriver driver = new RemoteWebDriver(
    new URL("http://localhost:4444/"),
    new HtmlUnitDriverOptions());

Getting/setting HtmlUnitDriver options:

In addition to methods for reading and writing specific HtmlUnitDriver options, you can use the standard Capabilities API:

  • is(String)
  • getCapability(String)
  • setCapability(String, Object)

Getting individual browser version traits:

HtmlUnitDriverOptions contains a BrowserVersion capability which can be read and written directly:

  • getWebClientVersion()
  • setWebClientVersion(BrowserVersion)

The individual traits of the BrowserVersion object can be read directly as well via the standard Capabilities API. For example:

HtmlUnitDriverOptions options = new HtmlUnitDriverOptions(BrowserVersion.EDGE);
// System time zone accessed via BrowserVersion API
TimeZone viaBrowserVersion = options.getWebClientVersion.getSystemTimezone();
// System time zone accessed via standard Capabilities API
TimeZone viaCapabilityName = (TimeZone) options.getCapability(BrowserVersionTrait.optSystemTimezone);

NOTE: Although HtmlUnitDriverOptions objects are mutable (their capabilities can be altered), the individual traits of the BrowserVersion object within these objects cannot be altered:

HtmlUnitDriverOptions options = new HtmlUnitDriverOptions(BrowserVersion.CHROME);
options.setCapability(BrowserVersionTrait.optUserAgent, "HtmlUnitDriver emulating Google Chrome");
// => UnsupporterOperationException: Individual browser version traits are immutable; 'optUserAgent' cannot be set

For more details, see The BrowserVersionTraits Enumeration below.

The HtmlUnitOption Enumeration

The HtmlUnitDriverOptions class provides a few targeted methods for manipulating frequently-used or complex capabilities (e.g. - isJavaScriptEnabled()). However, the majority of the capabilities of HtmlUnitDriver are manipulated via the standard Capabilities API as shown above. All of the capabilities defined by HtmlUnitDriver are represented in the HtmlUnitOption enumeration, which provides the capability names, accessors, and mutators for the browser options.

HtmlUnitOption/BrowserVersionTrait example usage:

HtmlUnitDriverOptions options = new HtmlUnitDriverOptions();
boolean popupBlockerEnabled = options.is(HtmlUnitOption.optPopupBlockerEnabled);
// NOTE: See subsection "Getting individual browser version traits" above
String  browserLanguage = (String) options.getCapability(BrowserVersionTrait.optBrowserLanguage);
options.setCapability(HtmlUnitOption.optGeolocationEnabled, true);
property namevalue typedefaultdescription
webClientVersionBrowserVersionBrowserVersion.BEST_SUPPORTEDBrowser version of this HtmlUnitDriver.
javascriptEnabledbooleantrueEnables/disables JavaScript support.
cssEnabledbooleantrue
Enables/disables CSS support. If disabled, HtmlUnit will not download linked CSS files and also not trigger the associated onload/onerror events.
printContentOnFailingStatusCodebooleantrue
Print document on failing status code. Specifies whether or not the content of the resulting document will be printed to the console in the event of a failing response code. Successful response codes are in the range 200-299.
throwExceptionOnFailingStatusCodebooleantrue
Throw exception on failing status code. Specifies whether or not an exception will be thrown in the event of a failing status code. Successful status codes are in the range 200-299.
throwExceptionOnScriptErrorbooleantrue
Throw exception on script error. Indicates if an exception should be thrown when a script execution fails or if it should be caught and just logged to allow page execution to continue.
popupBlockerEnabledbooleanfalse
Enable/disable the popup window blocker. By default, the popup blocker is disabled, and popup windows are allowed. When set to true, the window.open() function has no effect and returns null.
isRedirectEnabledbooleantrue
Enables/disables automatic redirection. Sets whether or not redirections will be followed automatically on receipt of a redirect status code from the server.
tempFileDirectoryFile(none) (use system default)
Directory for response content temporary files. Path to the directory to be used for storing the response content in a temporary file. The specified directory is created if it doesn't exist.
sslClientCertificateStoreKeyStore(none)
The SSL client certificate KeyStore to use. NOTE: This option is omitted when serializing session settings.
sslClientCertificateTypechar[](none)Type of the specified SSL client certificate KeyStore (e.g. - jks or pkcs12).
sslClientCertificatePasswordchar[](none)Password for the specified SSL client certificate KeyStore.
sslTrustStoreKeyStore(none)
The SSL server certificate trust store. All server certificates will be validated against this trust store.
sslTrustStoreTypechar[](none)Type of the specified SSL trust KeyStore (e.g. - jks or pkcs12).
sslTrustStorePasswordchar[](none)Password for the specified SSL trust KeyStore.
sslClientProtocolsString[](none) (use default protocols)Protocol versions enabled for use on SSL connections.
sslClientCipherSuitesString[](none) (use default suites)Cipher suites enabled for use on SSL connections.
geolocationEnabledbooleanfalseEnables/disables geo-location support.
doNotTrackEnabledbooleanfalseEnables/disables "Do Not Track" support.
homePageString"https://www.htmlunit.org/"Home page for this client.
proxyConfigProxyConfig(none)Proxy configuration for this client.
timeoutint90,000
WebConnection timeout for this client. Set to zero (0) for an infinite wait.
connectionTimeToLivelong-1L (use HTTP default)
HttpClient connection pool connTimeToLive (in milliseconds). Use this if you are working with web pages behind a DNS based load balancer.
useInsecureSSLbooleanfalse
Accept/reject connection to servers with expired or corrupt certificates. If set to true, the client will accept connections to any host, regardless of whether they have valid certificates or not. This is especially useful when you are trying to connect to a server with expired or corrupt certificates.
sslInsecureProtocolString(none) (use SSL)SSL protocol to use when USE_INSECURE_SSL is set to true.
maxInMemoryint500 * 1024
Maximum bytes to have in memory. Content that exceeds the specified maximum size is stored in a temporary file. Specifying 0 or -1 deactivates this storage feature.
historySizeLimitint50
Maximum number of pages to cache in history. HtmlUnit uses SoftReference<Page> for storing the pages that are part of the history. If you like to fine tune this, you can use HISTORY_PAGE_CACHE_LIMIT to limit the number of page references stored by the history.
historyPageCacheLimitintInteger.MAX_VALUE
Maximum number of pages to cache in history. If this value is smaller than HISTORY_SIZE_LIMIT, HtmlUnit will only use soft references for the first HISTORY_PAGE_CACHE_LIMIT entries in the history. For older entries, only the URL is saved; the page will be (re)retrieved on demand.
localAddressInetAddress(none) (use localhost)
Local address to be used for request execution. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates.
downloadImagesbooleanfalseEnables/disables automatic image downloading.
screenWidthint1920Screen width.
screenHeightint1080Screen height.
webSocketEnabledbooleantrueEnables/disables WebSocket support.
webSocketMaxTextMessageSizeint-1 (use default size)WebSocket maxTextMessageSize parameter.
webSocketMaxTextMessageBufferSizeint-1 (use default size)WebSocket maxTextMessageBufferSize parameter.
webSocketMaxBinaryMessageSizeint-1 (use default size)WebSocket maxBinaryMessageSize parameter.
webSocketMaxBinaryMessageBufferSizeint-1 (use default size)WebSocket maxBinaryMessageBufferSize parameter.
fetchPolyfillEnabledbooleanfalseEnables/disables fetch polyfill
fileProtocolForXMLHttpRequestsAllowedbooleanfalse
Allows/blocks file protocol for XMLHttpRequests. If set to true, the client will accept XMLHttpRequests to URLs using the file protocol. Allowing this introduces security problems and is therefore not allowed by current browsers. But some browsers have special settings to open this door; therefore, we have this option.

The BrowserVersionTrait Enumeration

The BrowserVersion capability of HtmlUnitDriverOptions is comprised of many individual traits, and each of these can be read discretely via the standard Capabiltiies API. Examples of this are shown above (e.g. - SYSTEM_TIME_ZONE). Note that these traits are immutable.

NOTE: Technically, the traits of BrowserVersion objects can be revised, but alterations made to existing instances aren't propagated to the associated HtmlUnitDriver; browser version traits are only imported en masse when a new browser version is specified. To avoid confusion, setting of individual traits is only supported via the BrowserVersionBuilder class.

For additional information, see Getting individual browser version traits above.

trait namevalue typedefaultdescription
numericCodeint0Returns the numeric code for the browser represented by this BrowserVersion.
nicknameString(none)Returns the nickname for the browser represented by this BrowserVersion.
applicationVersionString(none)
Returns the application version. e.g. - "4.0 (compatible; MSIE 6.0b; Windows 98)".
userAgentString(none)
Returns the user agent string. e.g. - "Mozilla/4.0 (compatible; MSIE 6.0b; Windows 98)"
applicationNameString(none)
Returns the application name. e.g. - "Microsoft Internet Explorer"
applicationCodeNameString"Mozilla"Returns the application code name.
applicationMinorVersionString"0"Returns the application minor version.
vendorString""
Returns the browser vendor. e.g. - "Google Inc."
browserLanguageString"en-US"Returns the browser language.
isOnlinebooleantrueReturns true if the browser is currently online.
platformString"Win32"Returns the platform on which the application is running.
systemTimezoneTimeZoneTimeZone.getTimeZone(      "America/New_York")Returns the system TimeZone.
acceptEncodingHeaderString(none)Returns the value used by the browser for the Accept-Encoding header.
acceptLanguageHeaderString(none)Returns the value used by the browser for the Accept-Language header.
htmlAcceptHeaderString(none)Returns the value used by the browser for the Accept header if requesting a page.
imgAcceptHeaderString(none)Returns the value used by the browser for the Accept header if requesting an image.
cssAcceptHeaderString(none)Returns the value used by the browser for the Accept header if requesting a CSS declaration.
scriptAcceptHeaderString(none)Returns the value used by the browser for the Accept header if requesting a script.
xmlHttpRequestAcceptHeaderString(none)Returns the value used by the browser for the Accept header if performing an XMLHttpRequest.
secClientHintUserAgentHeaderString(none)Returns the value used by the browser for the Sec-CH-UA header.
secClientHintUserAgentPlatformHeaderString(none)Returns the value used by the browser for the Sec-CH-UA-Platform header.

HtmlUnitOption and BrowserVersionTrait System Property Definitions

Each HtmlUnitOption property can be overridden by a corresponding Java system property whose name matches the pattern webdriver.htmlunit.<property-or-trait-name> (e.g. - webdriver.htmlunit.javascriptEnabled). If defined, these system properties are applied as default values when HtmlUnitDriver is instantiated. Subsequent requests to update corresponding capabilities on existing drivers are honored as expected.

Written with StackEdit.