HtmlUnit 5.8.0: Stricter Security, Smarter Storage, Real CSP
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, andscript-src-attr(withdefault-srcas fallback), including nonces, hashes,'unsafe-inline','unsafe-eval','unsafe-hashes', and'strict-dynamic'style-src,style-src-elem, andstyle-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 firesmedia-src: media URLs are checked; HtmlUnit does not load mediaobject-src: object and embed URLs are checked; HtmlUnit does not load the contentframe-src(with fallback tochild-srcanddefault-src): blocked frames showabout:blankworker-src(with fallback tochild-src,script-src, anddefault-src): blocked workers are not startedconnect-srcforWebSocket,navigator.sendBeacon(), andXMLHttpRequest(issue #638)base-uri: a blocked base URL is ignoredform-action: form submissions, includingformaction,javascript:URLs, and redirects, are checkedupgrade-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-uriviolation reports are sent as POST withapplication/csp-report. When simulating Firefox, the Firefox report format is used.- A new
ContentSecurityPolicyViolationListener, set withWebClient.setContentSecurityPolicyViolationListener(), receives all violations (enforced and report-only) from Java code.CollectingContentSecurityPolicyViolationListenercollects them, which makes it easy to fail a test on an unexpected violation. - The
securitypolicyviolationevent is supported with all its properties. - The
nonceproperty of HTML and SVG elements is supported. Like browsers, the nonce attribute is hidden when the policy comes from a header. CspQueries.isFetchDirectiveUnrestricted()andisBaseUriUnrestricted()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:, andblob:documents inherit a copy of the parent’s or opener’s policy. Documents written bydocument.open(),write(), orclose()keep the replaced document’s policy.eval()andnew Function()are checked against the policy of the window they belong to.frame-ancestorsis checked against all ancestors, not just the parent. AllContent-Security-Policyheaders are used, including comma-separated policies.X-Frame-OptionssupportsSAMEORIGINand is ignored if a policy containsframe-ancestors.- Policies from
metaelements ignoreframe-ancestors,sandbox, andreport-uri. Previously a meta element withsandboxcould 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()andtoDataURL()then throw aSecurityError. - Images with a
crossoriginattribute and a matchingAccess-Control-Allow-Originheader 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 anInvalidStateErrorfor 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:
sessionStorageis separated by origin; it was previously shared by all pages of a window.localStorageis 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’ssessionStorage. - Quota: The 5 MiB quota is shared by all
Storageobjects of the same storage area and counts both keys and values. Exceeding it throws aQuotaExceededError. - Properties: Stored items are visible as properties (
in,Object.keys(),hasOwnProperty(),for...in,delete). Missing arguments throw aTypeError. - storage events fire in other windows and frames that share the same storage area.
StorageEventsupportskey,oldValue,newValue,url,storageArea, andinitStorageEvent(). - Java API:
StorageHolder.getSessionStorage(WebWindow)returns the store for the current page’s origin. UsegetSessionStorage(WebWindow, URL)for a specific origin.
Cookies, History, and Security
document.cookie(andmeta http-equiv="set-cookie") no longer createsHttpOnlycookies, and it can no longer replace or delete an existingHttpOnlycookie (RFC 6265, section 5.3). Thanks to Vidya m.History.pushState()andHistory.replaceState()throw aSecurityErrorif 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 inAccess-Control-Allow-Methods. Thanks to Vidya m. - File URLs: Asynchronous XHR requests to
file:URLs no longer load the file whenWebClientOptions.isFileProtocolForXMLHttpRequestsAllowed()isfalse. 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 ajavascript:URL.
Downloads
WebResponse.getContentDisposition()returns the parsedContent-Dispositionheader and parses it only once.Attachment.getSuggestedFilenameFrom(ContentDisposition)letsAttachmentHandlerimplementations reuse it.AttachmentHandler.isAttachment()now detectsapplication/octet-streameven when the content type has parameters, such asapplication/octet-stream; charset=binary.
Serialization and the DOM
- XHTML serialization:
menuitemis no longer written as an empty-element tag in XHTML documents. - Empty elements:
asXml()andpage.save()write empty HTML elements such ash3,b,label, andsectionwith an end tag. Only void elements such asbr,img, andinputuse 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:
NamedNodeMapexposes attribute names as named properties.HTMLOptionsCollectionexposes option ids and names. Prototype properties such aslengthare no longer hidden by attributes. - Own properties: The indexed properties of
DOMTokenList,NamedNodeMap,StyleSheetList,CSSRuleList,CSSStyleDeclaration,HTMLOptionsCollection,HTMLSelectElement,HTMLFormElement,DOMRectList,FileList, andDataTransferItemListare now own properties.Object.keys(),Object.getOwnPropertyNames(), andfor...insee them.DOMStringMapentries are visible toinand to the same enumeration methods. - CSSRuleList no longer reports
lengthanditemas own properties. - cloneNode() no longer shares internal change listeners with the original, so a
MutationObserveron the original no longer sees changes made to the clone. - DOMTokenList.toggle() honors the optional
forceargument. Thanks to Vladimir Babin (issue #1188). - Node operations:
appendChild(),insertBefore(),replaceChild(), andremoveChild()throw aTypeErrorfor non-node arguments.replaceChild()throws aNotFoundErrorif the node to replace is not a child. - querySelector() and querySelectorAll() on
DomNodeare 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, socontentEditablereturns'true'.DomElement.ATTRIBUTE_VALUE_EMPTYis deprecated; check for an empty value withvalue.isEmpty(). - CSSStyleDeclaration.setProperty(name, value) without a priority was ignored. It now works.
- NodeIterator:
whatToShowis available from JavaScript.createNodeIterator()defaults toNodeFilter.SHOW_ALL. - Objects:
HTMLObjectElement.datais 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.
keyupfires 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, andlocationare correct for special keys, numpad keys, modifiers, and punctuation.keypressfires only for keys that produce a character. - Input events:
inputfires only when the text actually changes. It is now anInputEventwith the correctinputTypeanddata. - Modifier state:
getModifierState()is available onKeyboardEventandMouseEvent. - Textarea: Typing
\ror\r\ninserts a single line feed. - Autofocus: The
autofocusattribute is supported (issue #607). After the page loads, the first focusable element withautofocusgets focus. - Tabbable elements:
HtmlPage.getTabbableElements()no longer includes hidden inputs.
Canvas Drawing and Geometry
- Canvas fill:
fill()fills all subpaths as one shape. Theevenoddrule works, and holes made of subpaths drawn in the opposite direction render correctly. - Canvas text:
textAlignandtextBaselineare added. Both are used byfillText()and are saved and restored bysave()andrestore(). - DOMMatrix: Added
scale(),scale3d(),scaleNonUniform(),rotateFromVector(),transformPoint(), and many*Self()methods, plusfromMatrix(),fromFloat32Array(), andfromFloat64Array(). The constructor accepts CSS transform lists, such asnew 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(), andclamp()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+5and-1are accepted. The argument is parsed once instead of on every match. lch()andoklch()accept a plain number as hue, for exampleoklch(70% 0.1 200).min(),max(), andclamp()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:
trimLeftandtrimRightare aliases oftrimStartandtrimEndString.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
prototypeproperty. Arrow functions no longer have one in compiled mode. ++and--on super properties useToNumeric, so BigInt works, and non-constant element expressions are handled correctly- The
Proxyconstructor capability is no longer lost on revocation - Reading
stackfrom an error with a null prototype no longer throws aNullPointerException evaland theFunctionconstructors call a new hook,Context.ensureCanCompileStrings()
Other Improvements
HtmlLinkfires 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.onerroris 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
WebClientthat was deserialized can now run newsetTimeout()andsetInterval()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
innerHTMLordocument.write()during parsing. - Requests to public suffix hosts, such as
https://co.uk/, no longer throw aNullPointerExceptionwhen computingSec-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:
- Changes Report: Detailed release notes
- Details about HtmlUnit Security: Security considerations
- Maven Central: Download
- GitHub Repository: Source code