I just wanted to post an update regarding the current state of the WebView
of JavaFX 18, because we went with the suggested solution (setting the cookie manager before calling the web view) but still had issues.
The reason for this is the way the HTTP2Loader
class, that is used to make request in the WebEngine
, works:
// Use singleton instance of HttpClient to get the maximum benefits
@SuppressWarnings("removal")
private final static HttpClient HTTP_CLIENT =
AccessController.doPrivileged((PrivilegedAction<HttpClient>) () -> HttpClient.newBuilder()
.version(Version.HTTP_2) // this is the default
.followRedirects(Redirect.NEVER) // WebCore handles redirection
.connectTimeout(Duration.ofSeconds(30)) // FIXME: Add a property to control the timeout
.cookieHandler(CookieHandler.getDefault())
.build());
Because the HTTP_CLIENT
field is static
and used to execute the request, only the first time a HTTP2Loader
instance is created, will the current default CookieHandler
be referenced. So if you just set a new CookieHandler
every time before you load a page via the WebView
, then this will only work once. After that the HTTP_CLIENT
singleton will always use the CookieHandler
that is referenced when it was created.
IMHO this is a design issue in the HTTP2Loader
class. Instead of having a static
field, the field should be none static. The HTTP2Loader
class is effectively an immutable one time use instance anyway, so there is no need to make use of a singleton to execute a request.
I have no idea why they went with that solution, really. Even the javadoc does not make much sense, because what are the "benefits"?
So there are two solutions now:
- Access the current cookie handler an put an empty map for the URI that you will be accessing. E.g.
CookieHandler.getDefault().put(someUri, Collections.emptyMap())
Though this will be a problem if you access a side and a lot of redirects happen in the process, in which case there is no way to know about which URIs cookies to empty.
- Create a new CookieHandler before the first time a page in any WebView is loaded and keep track of it. Then before you load a WebView again, clear the CookieStore of the handler that you kept track of.
Now that being said, the afore mentioned methods will fail if another piece of code that you do not have control over does the following:
- Noted the current default
CookieHandler
- Set a new default
CookieHandler
- Created a
WebView
and loaded page for the first time
- Set the old
CookieHandler
as the default again
In that case you will never be able to gain access to the CookieHandler
again that is from there on out being used in the WebView
.