Search code examples
javajavafxsession-cookieshttpcookiejavafx-webengine

Delete specific cookies from webengine JavaFX


I would like to delete some specific HTTP only cookies generated by the JavaFX webengine. Chrome browser allows us to delete httponly cookie which means this is programmatically possible.

I am able to delete all cookies using

java.net.CookieManager manager = new java.net.CookieManager();
manager.getCookieStore().removeAll();

Using this the user is logged out from my application as well. I want to be able to delete all cookies except the one generated for my application. Or is it possible to delete the same cookies using javascript.


Solution

  • Anyone looking for the solution. Here it is. Set this right at the start of the main method of javafx.

    cookieManager =  new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);
    

    Then on any event(I did it onclick of a button) call this

    CookieStore cookieJar =  Main.cookieManager.getCookieStore();
    List<HttpCookie> cookies =  cookieJar.getCookies();
    
    for (HttpCookie ck: cookies) {
    if(ck.getName().equals("JSESSIONID")){
              System.out.println("JSESSIONID");
       }else{
              ck.setMaxAge(0);
              System.out.println("CookieHandler retrieved cookie: " + ck);
       }
    }
    

    I hope this helps someone cause I spent the entire day looking for the solution.