How to enable cookies in android webview?

2019-01-07 14:00发布

问题:

how do i enable cookies in a webview?

i tried to use

CookieManager.getInstance().setAcceptCookie(true);

just before calling WebView.loadUrl() and it doesnt work as i get a html page error from a website saying cookies need to be enabled.

What i dont understand is how does cookieManager know which webview to enable cookies?

say if i had a activity with two webviews in the screen and i only wanted one of those webviews to enable cookies, how is that possible using a CookieManager?

i feel like i am missing something? i could not find a method like webView.setCookieManager or Cookiemanager.setWebView(webview)

Thanks

回答1:

CookieManager.getInstance() is the CookieManager instance for your entire application. Hence, you enable or disable cookies for all the webviews in your application.

Normally it should work if your webview is already initialized: http://developer.android.com/reference/android/webkit/CookieManager.html#getInstance()

Maybe you call CookieManager.getInstance().setAcceptCookie(true); before you initialize your webview and this is the problem?



回答2:

You should consider that

CookieManager.getInstance().setAcceptCookie(true);

doesn't work from lollipop(API21) and above. You should check and use appropriate function for that case:

if (android.os.Build.VERSION.SDK_INT >= 21) {   
     CookieManager.getInstance().setAcceptThirdPartyCookies(mWebVIew, true);
 }else {
     CookieManager.getInstance().setAcceptCookie(true);
}