WebView and Cookies on Android


I have an application on appspot that works fine through regular browser, however when used through Android WebView, it cannot set and read cookies. I am not trying to get cookies "outside" this web application BTW, once the URL is visited by WebView, all processing, ids, etc. can stay there, all I need is session management inside that application. First screen also loads fine, so I know WebView + server interactivity is not broken.

I looked at WebSettings class, there was no call like setEnableCookies.

I load url like this:

public class MyActivity extends Activity {
  public void onCreate(Bundle savedInstanceState) {
    WebView webview = new WebView(this);
    webview.loadUrl([MY URL]);

Any ideas?

4/2/2010 12:00:54 PM

Accepted Answer

I figured out what's going on.

When I load a page through a server side action (a url visit), and view the html returned from that action inside a Webview, that first action/page runs inside that Webview. However, when you click on any link that are action commands in your web app, these actions start a new browser. That is why cookie info gets lost because the first cookie information you set for Webview is gone, we have a seperate program here.

You have to intercept clicks on Webview so that browsing never leaves the app, everything stays inside the same Webview.

  WebView webview = new WebView(this);      
  webview.setWebViewClient(new WebViewClient() {  
      public boolean shouldOverrideUrlLoading(WebView view, String url)  
        view.loadUrl(url); //this is controversial - see comments and other answers
        return true;  
  webview.loadUrl([MY URL]);

This fixes the problem.

5/13/2014 5:43:16 PM

If you are using Android Lollipop i.e. SDK 21, then:


won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow