I need to access all the cookies from a JavaFX WebView. As far as I can see there\'s a com.sun.webkit that implements its own CookieManager, Cookie, etc, etc. In that implem
(Updated after doing some research...)
Java's default implementation of CookieHandler
is java.net.CookieManager
, which provides the API and functionality I think you are looking for (supported by the CookieStore
and HttpCookie
classes). Referring to Setting a cookie using JavaFX's WebEngine/WebView and reading between the lines a little, it seems that java.net.CookieManager
supports an obsolete standard (RFC 2965), and because of that, the JavaFX team replaced it with a non-public-API class that (I am assuming) supports the later RFC 6265. The private-API implementation, com.sun.webkit.network.CookieManager
is not a subclass of java.net.CookieManager
and doesn't provide access to any of the other java.net
supporting classes. Note also that using any of the API from that class directly will prevent you updating to Java 9 at any point.
So I think you have two choices. If you can live with a RFC 2965-compliant implementation, all you need to do is to revert to the java.net.CookieManager
implementation: just call
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
after instantiating the WebView
. Then you can use the standard API to access details of the cookies:
cookieManager.getCookieStore().getCookies().forEach(cookie -> {
String name = cookie.getName();
String value = cookie.getValue();
String domain = cookie.getDomain();
long maxAge = cookie.getMaxAge(); // seconds
boolean secure = cookie.getSecure();
// etc...
});
Note that the HttpCookie
class defines a matching algorithm to determine if a particular host is part of a particular domain, so it avoids replicating cookies over multiple URIs belonging to the same domain.
If you need the more recent standard, then it seems you either have to do some fairly dirty hacking on the non-public classes, or you need to implement your own cookie handler (which as you've observed, is not a trivial task).
There is no direct way in java as far as I know, but you can communicate with the javascript side of a webPage, meaning you could do something like this: (not tested!)
WebView wv; //assumed to be initialized
WebEngine we = wv.getEngine();
String cookie = (String)we.executeScript("return document.cookie"):
Yes this means you got the usual restrictions to coockie acces as you normally have in javascript. But it might be enough in your case.
EDIT:
Apparently its also possible using the java.net library (e.g.
java.net.CoockieHandler.getDefault()
). In this SO post you can find a bit more on how to use it, and here is the CoockieManager documentation.