josemmo josemmo - 1 month ago 21
Ajax Question

Cordova session cookies don't work on Android Lollipop

I develop a Cordova/Phonegap app for Android which uses session cookies to login to third party websites.
For this, I do an AJAX post request (with jQuery) and then cookies are set automatically.

But, when I updated my smartphone to Android Lollipop 5.0 and also the app libraries to API level 21, cookies stopped working. What has changed?

Answer

After hours spent looking on the Internet for a working solution, I came across an article that explains the issue really well, so I am posting it here because I thought it will be useful to other Stack Overflow users.

Basically, the problem lies on the new Android third party cookies policy (https://developer.android.com/about/versions/android-5.0-changes.html#BehaviorWebView), which blocks them by default.

The solutions is to add a few lines of code to the main activity:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    super.init();

    // Allow third party cookies for Android Lollipop
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView webView = (WebView)super.appView;
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptThirdPartyCookies(webView,true);
    }

    super.loadUrl(Config.getStartUrl());
}

For more information, I put a link to the full article here: http://joashpereira.com/blog/2014/11/19/fix-to-cordovaphonegap-apps-targeting-android-5-lollipop-or-later-on-default-disallowing-third-party-cookies/