60

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 {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);       
    WebView webview = new WebView(this);
    setContentView(webview);      
    webview.loadUrl([MY URL]);
  }
  .. 
}

Any ideas?

burak bayramli
  • 1,037
  • 1
  • 10
  • 9

5 Answers5

99

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

CookieManager.getInstance().setAcceptCookie(true);

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.

azizbekian
  • 60,783
  • 13
  • 169
  • 249
Huzefa Gadi
  • 1,129
  • 1
  • 7
  • 11
48

From the Android documentation:

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.

To use the CookieSyncManager, the host application has to call the following when the application starts:

CookieSyncManager.createInstance(context)

To set up for sync, the host application has to call

CookieSyncManager.getInstance().startSync()

in Activity.onResume(), and call

 CookieSyncManager.getInstance().stopSync()

in Activity.onPause().

To get instant sync instead of waiting for the timer to trigger, the host can call

CookieSyncManager.getInstance().sync()

The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.

Finally something like this should work:

// use cookies to remember a logged in status   
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);      
webview.loadUrl([MY URL]);
redochka
  • 12,345
  • 14
  • 66
  • 79
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • Tried this, but I am not trying to take cookies out of webview. Cookies can disappear between two seperate Webview loadUrl calls, that's fine. My problem is cookies are not working "within" the same session. – burak bayramli Apr 02 '10 at 13:05
  • Check out also this: http://stackoverflow.com/questions/1652850/android-webview-cookie-problem – Pentium10 Apr 02 '10 at 13:10
  • 5
    In addition, you need to call CookieManager.setAcceptFileSchemeCookies(true) when Build.VERSION.SDK_INT >= 12, if you are using the WebView to reference assets stored on the local filesystem. This call must be PRIOR to first instantiation of a CookieSyncManager or CookieManager. – Robin Davies Dec 05 '12 at 13:25
  • @RobinDavies you saved my day! – Mandrake Jun 10 '15 at 22:09
  • 1
    From the documentation: "This class was deprecated in API level 21. The WebView now automatically syncs cookies as necessary. You no longer need to create or use the CookieSyncManager. To manually force a sync you can use the CookieManager method CookieManager#flush which is a synchronous replacement for sync()." – Daniel Alder Aug 20 '20 at 23:47
  • CookieSyncManager is now deprecated. – Rohit Singh Jan 10 '23 at 23:26
39

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() {  
      @Override  
      public boolean shouldOverrideUrlLoading(WebView view, String url)  
      {  
        view.loadUrl(url); //this is controversial - see comments and other answers
        return true;  
      }  
    });                 
  setContentView(webview);      
  webview.loadUrl([MY URL]);

This fixes the problem.

Chris Stratton
  • 39,853
  • 6
  • 84
  • 117
burak bayramli
  • 1,037
  • 1
  • 10
  • 9
  • 41
    Actually when overriding `shouldOverrideUrlLoading` to make your `WebView` handle all URL links, it should simply `return false`. No need for `view.loadUrl(url);`. Returning true actually means you **want** the system to override the handling (probably to launch a browser). So if you want links to open in your webview, just return false. Source: http://developer.android.com/guide/webapps/webview.html#HandlingNavigation – Tony Chan Jul 12 '12 at 00:49
  • 3
    Wrong. Wrong. Wrong. Turbo is right: you absolutely should NOT be calling view.loadUrl() in this call back. – Brian Melton-Grace - MSFT Nov 26 '13 at 19:11
  • 5
    Right or wrong, 3rd parties should not be making fundamental changes to the code of an answer. Post your own answer or upvote a critical comment if you agree with it. – Chris Stratton May 13 '14 at 17:42
  • 1
    bad bad bad, return false! – user25 Aug 28 '16 at 17:44
9

My problem is cookies are not working "within" the same session. –

Burak: I had the same problem. Enabling cookies fixed the issue.

CookieManager.getInstance().setAcceptCookie(true);
Lucifer
  • 29,392
  • 25
  • 90
  • 143
Phil
  • 89
  • 1
  • 1
  • Hi Lucifer I tried this but i am not able to store the mail id and password details in cookies. Does webview store the details or not? pls help me. When i am entered the id and pwd for the first time, these details should be saved, when i am going to login with same userid and pwd those should be stored in cookies and should be displayed and then i have to select that id. Is it possible in webview to store details in cookes or not? Thanks and regards in advance. –  Jun 13 '12 at 04:55
  • i also followed this link http://stackoverflow.com/questions/5404274/make-android-webview-not-store-cookies-or-passwords –  Jun 13 '12 at 05:01
  • 1
    This suggestion fixed my problem with lost cookies between app restarts on Android 2.2.1 – zasadnyy Oct 23 '12 at 07:45
  • For full solution, check the answer https://stackoverflow.com/a/47868677/3101777 – Misha Akopov Aug 31 '20 at 08:02
1

CookieManager.getInstance().setAcceptCookie(true); Normally it should work if your webview is already initialized

or try this:

CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
Miro
  • 125
  • 1
  • 11