capacitor: bug: cookies not being persisted

Bug Report

Capacitor Version

npx cap doctor output: @capacitor/ios not installed @capacitor/cli 1.5.2 @capacitor/core 1.5.2 @capacitor/android 2.1.0

Affected Platform(s)

  • Android
  • iOS
  • Electron
  • Web

Current Behavior

Android native Cookies management persists cookies only after a given amout of time. This causes problems when an auth session cookie or remember me cookie are used and the application is destroyed shortly after the login (or any other action creating a cookie) is performed. When re-started, we won’t have that cookie available.

A similar problem is present on iOS too, but haven’t yet tried it out (link at the end of the issue).

Expected Behavior

Cookies shall be forcefully persisted when onPause or onStop is called, to be sure to avoid data loss in case the app is later destroyed (by the user or by the system).

Sample Code or Sample Application Repo


Reproduction Steps

  • perform a request to a server which you know will set a cookie
  • hard-close the app right after
  • re-open the app
  • check via chrome devtools that the cookie isn’t present

Other Technical Details

yarn --version output: 1.22

node --version output: 13.x

Other Information

This article explain the problem pretty well.

https://github.com/ionic-team/capacitor/issues/2347 seems to report the same problem https://github.com/ionic-team/capacitor/issues/2831 seems to be related, but not sure

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 18 (1 by maintainers)

Most upvoted comments

Simply adding the following to my MainActivity.java fixed the problem. Could probably be onStop instead, but I’m not sure if Android persist cookies even when the app is paused

import android.webkit.CookieManager;

public class MainActivity extends BridgeActivity {
  // ...

  @Override
  public void onPause() {
    super.onPause();

    CookieManager.getInstance().flush();
  }

  // ...
}

I can confirm that @IlCallo solution indeed solves the problem, but shouldn’t this be achieved by Capacitor itself? Or at least be part of Android template for new projects? As the current behavior (cookie state not being immediately persisted on Android) is definitely unexpected.