Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Facebook login state in a webView always returns unknown

I am developing a webapp that is wrapped in a native app for both iOS and Android. This is done by simply displaying the webapp in a webView for both platforms. I am having issues with the Facebook login and the Android platform.

Logging in to Facebook works via my "hack" but when the application is checking the login state afterwards it always returns unknown (which indicates that the SDK does not know if the user is logged into Facebook or not).

The webView:

WebView mainWebView = (WebView) findViewById(R.id.petpulseWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.clearCache(true);

The Javascript code:

// This function works, user is redirected to the Facebook login like he/she should
$(document).on('click', '#loginfb', function (e) {
    e.preventDefault();
    $.mobile.loading('show');

    // Worst hack.ever
    window.location.href = 'https://m.facebook.com/v2.2/dialog/oauth?client_id=xxxxx&response_type=code&redirect_uri=' + encodeURIComponent($('#base_url').val() + 'index.php?id=4') + '&scope=email&timestamp=';
});

// Checking if both the Facebook SDK and the correct page is loaded, if the user has code in GET he/she has been redirected from a Facebook login
function check_all_loaded () {
    if (loaded_page && loaded_facebook) {
        if (document.URL.indexOf('code=') >= 0) {
            FB.getLoginStatus(function(response) {
                // This always returns "unknown"
                console.log(response.status);
            });
        }
    }
}

After extensive testing I am lead to belive this is due to some sort of policy or something in the Android webView that "blocks" the request Facebook does to check the login state. This code works for all desktop browser and its iOS equivalent.

Is there some setting or option that would block this from working like it should in Android?

like image 890
OptimusCrime Avatar asked Mar 18 '23 05:03

OptimusCrime


1 Answers

I was right, it was due to third party cookies.

Adding these lines fixed the problem:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    CookieManager.getInstance().setAcceptThirdPartyCookies(mainWebView, true);
}

According to the documentation:

Apps that target KITKAT or below default to allowing third party cookies. Apps targeting LOLLIPOP or later default to disallowing third party cookies.

Which means that for versions lower than Lollipop does not need this fix.

like image 182
OptimusCrime Avatar answered Apr 06 '23 07:04

OptimusCrime