Home » Android » How to enable cookies in android webview?

How to enable cookies in android webview?

Posted by: admin April 23, 2020 Leave a comment

Questions:

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

How to&Answers:

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?

Answer:

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);
}