Remove all cookies from specific domain in web view

匿名 (未验证) 提交于 2019-12-03 08:50:26

问题:

I am trying to remove all the cookies from some domain, is there a way to do this?

The only method i saw is removeAllCookies.

Thank you.

回答1:

As per documentation, we don't have a method for removing individual cookies. But we could use an interesting work around with setCookie() to clear a site's cookies. as,

public abstract void setCookie (String url, String value)

Sets a cookie for the given URL. Any existing cookie with the same host, path and name will be replaced with the new cookie. The cookie being set will be ignored if it is expired.

So, the solution is, As mentioned in this answer, we need to manually clean up each cookie for each host key. eg:- facebook

android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "locale="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "datr="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "s="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "csm="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "fr="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "lu="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "c_user="); android.webkit.CookieManager.getInstance().setCookie(".facebook.com", "xs="); 


回答2:

First of all I can suggest you to have a look at CookieManager class which manages the cookies used by WebView. There was a method removeAllCookie() for clearing the cookies but It was deprecated in API level 21, So instead of this you can use removeAllCookeis(callback) method. You can pass null as the callback if you don't need to know when the operation completes or whether any cookie were removed, and in this case it is safe to call the method from a thread without a Looper.

To clear cookies in lollipop or more you can use

CookieManager.getInstance().removeAllCookies(null); CookieManager.getInstance().flush(); 

and in rest

CookieSyncManager cookieSyncMngr=CookieSyncManager.createInstance(context); cookieSyncMngr.startSync(); CookieManager cookieManager=CookieManager.getInstance(); cookieManager.removeAllCookie(); cookieManager.removeSessionCookie(); cookieSyncMngr.stopSync(); cookieSyncMngr.sync(); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!