Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webview cannot accept cookies

I'm creating a WebView based Android app that enables the user to login onto a mobile operator. When I run the app the WebView opens the website but I get a message that the WebView doesn't allow cookies. I've tried various codes that I found here but none of them worked. Can anyone help me? Here is the code I'm using:

//in oncreate
final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
final CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
String[] cookies = getCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register");
for (String cookie : cookies) {
    cookieManager.setCookie("https://myaccount.ee.co.uk/login-dispatch/?fa=register", cookie);
}
cookieSyncManager.sync();
webView.loadUrl("https://myaccount.ee.co.uk/login-dispatch/?fa=register");

and the getCookies method:

public String[] getCookie(String siteName) {
     CookieManager cookieManager = CookieManager.getInstance();
     String cookies = cookieManager.getCookie(siteName);
     String[] cookiesArray = cookies.split(";");
     return cookiesArray;
}
like image 289
Darko Petkovski Avatar asked Nov 30 '15 12:11

Darko Petkovski


People also ask

How do I enable cookies on WebView?

How do I enable cookies in a webview? CookieManager. getInstance(). setAcceptCookie(true);

Do cookies work in WebView?

Bookmark this question. Show activity on this post. I have an application on appspot that works fine through regular browser, however when used through Android WebView, it cannot set and read cookies.

Why is my WebView not working?

You might often face issues in updating the chrome and Android System Webview. To fix this problem, you can reboot your device, check your internet connection, stop auto-updating all apps, clear Google Playstore cache, and storage, leave the beta testing program, and manually update Android WebView app from Playstore.


1 Answers

Try to override the shouldOverrideUrlLoading method to make your WebView handle all URL links, and not start a new browser on any link.

webview.setWebViewClient(new WebViewClient() {  
          @Override  
          public boolean shouldOverrideUrlLoading(WebView view, String url)  
          {  
            return false;  
          }  
});   

webview.loadUrl(url);

If this doesn't work you can replace your

cookieManager.setAcceptCookie(true);

to

cookieManager.setAcceptThirdPartyCookies(true);

because cookieManager.setAcceptCookie(true); doesn't work on Lollipop.

like image 174
Vasileios Pallas Avatar answered Sep 28 '22 04:09

Vasileios Pallas