HtmlUnit 5.8.0 is one of our biggest releases yet, and it moves the project closer to real browser behavior in many areas at once. The headline feature is a broad expansion of Content Security Policy (CSP) support, which now covers most of the directives that matter on real pages. Around it sits a long list of security hardening changes, storage and origin handling that now matches browsers, canvas and keyboard behavior that is much closer to real browsers, and many smaller DOM, CSS, and JavaScript fixes. Together with the Rhino team, we keep working through the details that make HtmlUnit behave like a real browser.

🚀 Version 5.8.0 - November 17, 2026

Content Security Policy

This is the biggest theme of the release. HtmlUnit now enforces CSP for many more resource types and reports violations the way browsers do.

New directives

  • script-src, script-src-elem, and script-src-attr (with default-src as fallback), including nonces, hashes, 'unsafe-inline', 'unsafe-eval', 'unsafe-hashes', and 'strict-dynamic'
  • style-src, style-src-elem, and style-src-attr: blocked styles are not applied. Like browsers, CSSOM changes are not checked.
  • img-src: blocked images are not downloaded, and the error event fires
  • media-src: media URLs are checked; HtmlUnit does not load media
  • object-src: object and embed URLs are checked; HtmlUnit does not load the content
  • frame-src (with fallback to child-src and default-src): blocked frames show about:blank
  • worker-src (with fallback to child-src, script-src, and default-src): blocked workers are not started
  • connect-src for WebSocket, navigator.sendBeacon(), and XMLHttpRequest (issue #638)
  • base-uri: a blocked base URL is ignored
  • form-action: form submissions, including formaction, javascript: URLs, and redirects, are checked
  • upgrade-insecure-requests: HTTP and WS URLs are upgraded to HTTPS and WSS, except for loopback hosts and report-only policies. Redirect targets are upgraded too.
  • Redirect targets of stylesheets (including @import), scripts, and images are checked against the policy

Reporting and testing

  • report-uri violation reports are sent as POST with application/csp-report. When simulating Firefox, the Firefox report format is used.
  • A new ContentSecurityPolicyViolationListener, set with WebClient.setContentSecurityPolicyViolationListener(), receives all violations (enforced and report-only) from Java code. CollectingContentSecurityPolicyViolationListener collects them, which makes it easy to fail a test on an unexpected violation.
  • The securitypolicyviolation event is supported with all its properties.
  • The nonce property of HTML and SVG elements is supported. Like browsers, the nonce attribute is hidden when the policy comes from a header.
  • CspQueries.isFetchDirectiveUnrestricted() and isBaseUriUnrestricted() were added. Thanks to Rick Mitchell for this.
  • A new documentation page, “Content Security Policy”, describes the support in detail.

Policy inheritance and parsing

  • about:blank, data:, and blob: documents inherit a copy of the parent’s or opener’s policy. Documents written by document.open(), write(), or close() keep the replaced document’s policy.
  • eval() and new Function() are checked against the policy of the window they belong to.
  • frame-ancestors is checked against all ancestors, not just the parent. All Content-Security-Policy headers are used, including comma-separated policies. X-Frame-Options supports SAMEORIGIN and is ignored if a policy contains frame-ancestors.
  • Policies from meta elements ignore frame-ancestors, sandbox, and report-uri. Previously a meta element with sandbox could block all scripts.
  • Invalid nonces and hashes are rejected.

Canvas Security

Canvas now follows the browser rules for cross-origin images:

  • Drawing an image from another origin (also via redirect) into a canvas taints it. getImageData() and toDataURL() then throw a SecurityError.
  • Images with a crossorigin attribute and a matching Access-Control-Allow-Origin header do not taint the canvas. If the CORS check fails, the image is broken and its error event fires.
  • Setting the width or height of a canvas, even to its current value, clears the bitmap and resets the 2D drawing state. For Chrome/Edge, the origin-clean flag is reset too.
  • A new method, HtmlImage.isBroken(), is available. drawImage() throws an InvalidStateError for a broken image, such as one that failed to download, was blocked by CSP, or failed the CORS check.

Storage and Origin Isolation

Storage was one of the areas where HtmlUnit differed most from browsers. It now behaves much more like them:

  • Origin separation: sessionStorage is separated by origin; it was previously shared by all pages of a window. localStorage is separated by origin too, so pages on the same host with different ports no longer share storage. Thanks to Vidya m for this.
  • about:blank iframes use the local and session storage of the parent page. A window opened with window.open() starts with a copy of the opener’s sessionStorage.
  • Quota: The 5 MiB quota is shared by all Storage objects of the same storage area and counts both keys and values. Exceeding it throws a QuotaExceededError.
  • Properties: Stored items are visible as properties (in, Object.keys(), hasOwnProperty(), for...in, delete). Missing arguments throw a TypeError.
  • storage events fire in other windows and frames that share the same storage area. StorageEvent supports key, oldValue, newValue, url, storageArea, and initStorageEvent().
  • Java API: StorageHolder.getSessionStorage(WebWindow) returns the store for the current page’s origin. Use getSessionStorage(WebWindow, URL) for a specific origin.

Cookies, History, and Security

  • document.cookie (and meta http-equiv="set-cookie") no longer creates HttpOnly cookies, and it can no longer replace or delete an existing HttpOnly cookie (RFC 6265, section 5.3). Thanks to Vidya m.
  • History.pushState() and History.replaceState() throw a SecurityError if the URL is not same-origin with the document. Previously a page could change its URL, and with it its origin for cookies, XMLHttpRequest, and local files, to any other URL. Also thanks to Vidya m.
  • CORS preflight responses are checked the way real browsers check them. Credentialed requests need the exact origin and Access-Control-Allow-Credentials, and the wildcard * is not accepted for them. Methods other than GET, HEAD, and POST must be listed in Access-Control-Allow-Methods. Thanks to Vidya m.
  • File URLs: Asynchronous XHR requests to file: URLs no longer load the file when WebClientOptions.isFileProtocolForXMLHttpRequestsAllowed() is false. Also thanks to Vidya m.
  • XMLHttpRequest from about:blank uses the origin of the creator (parent or opener).
  • Serialized attributes: The ampersand in attribute values is written as &. A parse-serialize-parse round trip used to decode character references twice, which could turn an inert value into a javascript: URL.

Downloads

  • WebResponse.getContentDisposition() returns the parsed Content-Disposition header and parses it only once. Attachment.getSuggestedFilenameFrom(ContentDisposition) lets AttachmentHandler implementations reuse it.
  • AttachmentHandler.isAttachment() now detects application/octet-stream even when the content type has parameters, such as application/octet-stream; charset=binary.

Serialization and the DOM

  • XHTML serialization: menuitem is no longer written as an empty-element tag in XHTML documents.
  • Empty elements: asXml() and page.save() write empty HTML elements such as h3, b, label, and section with an end tag. Only void elements such as br, img, and input use the empty-element form. The output can be parsed again as HTML without changing the structure. Thanks to Ronny Shapiro for this fix.
  • Named properties: NamedNodeMap exposes attribute names as named properties. HTMLOptionsCollection exposes option ids and names. Prototype properties such as length are no longer hidden by attributes.
  • Own properties: The indexed properties of DOMTokenList, NamedNodeMap, StyleSheetList, CSSRuleList, CSSStyleDeclaration, HTMLOptionsCollection, HTMLSelectElement, HTMLFormElement, DOMRectList, FileList, and DataTransferItemList are now own properties. Object.keys(), Object.getOwnPropertyNames(), and for...in see them. DOMStringMap entries are visible to in and to the same enumeration methods.
  • CSSRuleList no longer reports length and item as own properties.
  • cloneNode() no longer shares internal change listeners with the original, so a MutationObserver on the original no longer sees changes made to the clone.
  • DOMTokenList.toggle() honors the optional force argument. Thanks to Vladimir Babin (issue #1188).
  • Node operations: appendChild(), insertBefore(), replaceChild(), and removeChild() throw a TypeError for non-node arguments. replaceChild() throws a NotFoundError if the node to replace is not a child.
  • querySelector() and querySelectorAll() on DomNode are available again. They were removed in 5.7.0 by mistake. The node itself is the scope for :scope, as in browsers.
  • Empty attribute values: After serialization, attributes like contenteditable="" are detected as empty again, so contentEditable returns 'true'. DomElement.ATTRIBUTE_VALUE_EMPTY is deprecated; check for an empty value with value.isEmpty().
  • CSSStyleDeclaration.setProperty(name, value) without a priority was ignored. It now works.
  • NodeIterator: whatToShow is available from JavaScript. createNodeIterator() defaults to NodeFilter.SHOW_ALL.
  • Objects: HTMLObjectElement.data is implemented.
  • document.open() removes all event listeners and handlers from the document, its nodes, and the window.

Keyboard, Focus, and Input

Typing behavior moved closer to real browsers, driven mostly by issue #722:

  • Tab navigation: Tab moves focus to the next element, and Shift+Tab to the previous one. keyup fires on the newly focused element, and the text of a focused text input is selected. Tab on the last element moves focus out of the page.
  • KeyboardEvent: key, code, and location are correct for special keys, numpad keys, modifiers, and punctuation. keypress fires only for keys that produce a character.
  • Input events: input fires only when the text actually changes. It is now an InputEvent with the correct inputType and data.
  • Modifier state: getModifierState() is available on KeyboardEvent and MouseEvent.
  • Textarea: Typing \r or \r\n inserts a single line feed.
  • Autofocus: The autofocus attribute is supported (issue #607). After the page loads, the first focusable element with autofocus gets focus.
  • Tabbable elements: HtmlPage.getTabbableElements() no longer includes hidden inputs.

Canvas Drawing and Geometry

  • Canvas fill: fill() fills all subpaths as one shape. The evenodd rule works, and holes made of subpaths drawn in the opposite direction render correctly.
  • Canvas text: textAlign and textBaseline are added. Both are used by fillText() and are saved and restored by save() and restore().
  • DOMMatrix: Added scale(), scale3d(), scaleNonUniform(), rotateFromVector(), transformPoint(), and many *Self() methods, plus fromMatrix(), fromFloat32Array(), and fromFloat64Array(). The constructor accepts CSS transform lists, such as new DOMMatrix('translate(10px, 20px) rotate(45deg)'). Several NaN and Infinity cases are fixed, and setting a 3D value makes the matrix 3D.
  • CSS math: calc(), min(), max(), and clamp() are evaluated when computing element width and height (issue #363). They used to resolve to 0px.

CSS

  • :nth-child(An+B of S) and :nth-last-child(An+B of S) are supported.
  • The nth-*() arguments follow the An+B syntax, so :nth-child(2n + 1) and signed numbers like +5 and -1 are accepted. The argument is parsed once instead of on every match.
  • lch() and oklch() accept a plain number as hue, for example oklch(70% 0.1 200).
  • min(), max(), and clamp() are parsed as math functions.
  • In calc(), the + and - operators must be surrounded by whitespace.
  • Selectors with comments between simple selectors, such as div /* c */ p, are no longer dropped.

Rhino and JavaScript

Together with the Rhino team:

  • trimLeft and trimRight are aliases of trimStart and trimEnd
  • String.prototype.indexOf() with an empty search and a negative position is fixed
  • Multiplying '0' by a negative integer is fixed
  • Number.prototype.toString(radix) no longer drops the sign between -1 and 0
  • Generator methods have a prototype property. Arrow functions no longer have one in compiled mode.
  • ++ and -- on super properties use ToNumeric, so BigInt works, and non-constant element expressions are handled correctly
  • The Proxy constructor capability is no longer lost on revocation
  • Reading stack from an error with a null prototype no longer throws a NullPointerException
  • eval and the Function constructors call a new hook, Context.ensureCanCompileStrings()

Other Improvements

  • HtmlLink fires its load or error event after the stylesheet is stored, so reading styles in the handler no longer reloads it.
  • Workers created inside a function now deliver messages, and Worker.onerror is available.
  • Replacing a window’s page waits up to 10 seconds for the running JavaScript job. A job that is still running afterward is stopped and cannot modify the new page (issue #8).
  • A WebClient that was deserialized can now run new setTimeout() and setInterval() jobs.
  • Postponed actions, such as a form submit or a navigation, are no longer lost when another thread clicks at the same time. Snippet parsing state is kept per thread, so scripts and frames are no longer ignored when a timer uses innerHTML or document.write() during parsing.
  • Requests to public suffix hosts, such as https://co.uk/, no longer throw a NullPointerException when computing Sec-Fetch-Site.
  • Unit tests can use new assertEquals(..., maxWaitTime) variants, which retry until the expected value appears. This replaces many fixed waits.
  • Dependencies: commons-lang3 is upgraded to 3.22.0 and Jetty for websocket-client to 12.1.15.

Version 5.8.0 is available on Maven Central. Check out the full changes report for the complete list of changes.

Thanks to Vidya m for the CORS, file URL, cookie, history, and storage fixes; to Ronny Shapiro for the XML serialization fix; to Rick Mitchell for the CSP query methods; and to Vladimir Babin for the DOMTokenList fix. Thanks also to everyone who reported the issues behind #8, #363, #607, #638, #722, and #1188, and to the Rhino team for the steady JavaScript work.

Happy testing!

— RBRi


Resources: