Android WebView for Facebook Like Button

Stefan picture Stefan · Feb 24, 2011 · Viewed 18.5k times · Source

I'm trying to make facebook like functionality in Android WebView (project specification does not allow browser opening, or any out of application activity).

So, restrictions are that it has to be done in WebView. I've managed to make it a dialog, and apon user's click like button, it (the WebView) redirects successfully (in the same view) to facebooks login page. After successful authentication, the WebView (in a dialog) is redirected to blank page with facebook header.

Interestingly enough, when user leaves the blank dialog and click again on the like button it works like perfectly (like and unlike) - it somehow keeps authentication active. To resolve the blank page, I've tried/used following:

  • using WebViewClient and shouldOverloadUrlForwarding to keep whole process in same WebView dialog.
  • using WebChromeClient to properly execute JavaScript - without it after login is not possible to like/unlike.
  • tried using setUserAgentString() to simulate other browsers like Chrome or Firefox
  • tried the SSL Error certificate handling (in API level 8) (at WebViewClient)

    @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); }

  • using (and all possible combination of these)

    webView.getSettings().setAppCacheEnabled(true); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

  • Tried also persisting cookies with CookieSyncManager, CookieManager and manually handling.

All of this was with no result. I really appreciate any help!

Answer

Blundell picture Blundell · Aug 22, 2011

To get past the blank page you do this:

 webview.setWebViewClient(new LikeWebviewClient(this));

 private class LikeWebviewClient extends WebViewClient {        
    @Override
    public void onPageFinished(WebView view, String url) {
        Log.d(TAG, "onPageFinished url: " +url);
        // Facebook redirects to this url once a user has logged in, this is a blank page so we override this
        // http://www.facebook.com/connect/connect_to_external_page_widget_loggedin.php?............
        if(url.startsWith("http://www.facebook.com/connect/connect_to_external_page_widget_loggedin.php")){
            String redirectUrl = getFacebookLikeUrl();
            view.loadUrl(redirectUrl);
            return;
        }
        super.onPageFinished(view, url);
    }
}