8

I am new to android development. Trying to integrate FB and Google+ login in Android web view. FB login is working fine. But Google login is not allowing to login. I referred a few links but unable to succeed.

Problem is after providing user name and password in Gmail my web site is not sign in

A webview overlay over another webview

Google sign in not working android webview app

Google sign in not working android webview app

private class MyCustomWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        String host = Uri.parse(url).getHost();
        Log.d("Loading URL", url);
        if (host.equals(target_url_prefix)) {
            // This is my web site, so do not override; let my WebView load
            // the page
            if (mWebviewPop != null) {
                mWebviewPop.setVisibility(View.GONE);
                mContainer.removeView(mWebviewPop);
                mWebviewPop = null;
            }
            return false;
        }

        if (host.contains("m.facebook.com") || host.contains("facebook.co")
                || host.contains("google.co")
                || host.contains("www.facebook.com")
                || host.contains(".google.com")
                || host.contains(".google")
                || host.contains("accounts.google.com/signin/oauth/consent")
                || host.contains("accounts.youtube.com")
                || host.contains("accounts.google.com")
                || host.contains("accounts.google.co.in")
                || host.contains("www.accounts.google.com")
                || host.contains("oauth.googleusercontent.com")
                || host.contains("content.googleapis.com")
                || host.contains("ssl.gstatic.com")
            //     || host.contains("https://accounts.google.com/signin/oauth/consent")

        ) {
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch
        // another Activity that handles URLs

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        Log.d("onReceivedSslError", "onReceivedSslError");
        super.onReceivedSslError(view, handler, error);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (url.startsWith("https://m.facebook.com/v2.7/dialog/oauth")


        ) {
            if (mWebviewPop != null) {
                mWebviewPop.setVisibility(View.GONE);
                mContainer.removeView(mWebviewPop);
                mWebviewPop = null;
            }
            view.loadUrl("https://www.cbazaar.com");
            return;
        }

        super.onPageFinished(view, url);
    }
}

private class UriWebChromeClient extends WebChromeClient {

    @Override
    public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
        mWebviewPop = new WebView(mContext);
        mWebviewPop.setVerticalScrollBarEnabled(false);
        mWebviewPop.setHorizontalScrollBarEnabled(false);
        mWebviewPop.setWebViewClient(new MyCustomWebViewClient());
        mWebviewPop.setWebChromeClient(new UriWebChromeClient());
        mWebviewPop.getSettings().setJavaScriptEnabled(true);
        mWebviewPop.clearHistory();
        mWebviewPop.clearFormData();
        mWebviewPop.clearCache(true);
        mWebviewPop.getSettings().setSavePassword(true);
        mWebviewPop.getSettings().setSaveFormData(true);
        mWebviewPop.getSettings().setUserAgentString(USER_AGENT_FAKE);

        builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();

        builder.setTitle("");
        builder.setView(mWebviewPop);

        builder.setButton("close", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                mWebviewPop.destroy();
                dialog.dismiss();

            }
        });

        builder.show();
        builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

             /*   CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    cookieManager.setAcceptThirdPartyCookies(mWebviewPop,true);
                }
    */

        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        transport.setWebView(mWebviewPop);
        resultMsg.sendToTarget();

        return true;
    }


    @Override
    public void onCloseWindow(WebView window) {

        try {
            mWebviewPop.destroy();
        } catch (Exception e) {
        }

        try {
            builder.dismiss();

        } catch (Exception e) {
        }

    }

}
Zain Aftab
  • 709
  • 7
  • 21
Girish M
  • 81
  • 1
  • 1
  • 3

4 Answers4

11

Google does not allow default implementations of WebView to be used. Therefore you need to set a custom User-Agent to your WebView:

webView.getSettings().setUserAgentString("YourAppName");

You can use any string instead of YourAppName.

Vladyslav Matviienko
  • 10,129
  • 4
  • 29
  • 51
10

You have to create a custom webchromeclient and handle the popup from webview. Whenever there will requirement of popup from website, you have to load it in alert dialog.

public class WebViewActivity extends AppCompatActivity {

private WebView webViewPopUp;
private AlertDialog builder;
private Context globalContext;

private String url = "https://www.bellyfulstore.com/";

private WebView webView;
private String userAgent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view);

    webView = findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    webView.loadUrl(url);

    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Set User Agent
    userAgent = System.getProperty("http.agent");
    webSettings.setUserAgentString(userAgent + "yourAppName");

    // Enable Cookies
    CookieManager.getInstance().setAcceptCookie(true);
    if(android.os.Build.VERSION.SDK_INT >= 21)
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

    // Handle Popups
    webView.setWebChromeClient(new CustomChromeClient());
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setSupportMultipleWindows(true);
    globalContext = this.getApplicationContext();

    // WebView Tweaks
    webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    webSettings.setAppCacheEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    webSettings.setUseWideViewPort(true);
    webSettings.setSaveFormData(true);
    webSettings.setEnableSmoothTransition(true);
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);



    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            findViewById(R.id.progressBar).setVisibility(View.VISIBLE);

        }

        public void onPageFinished(WebView view, String url) {
            // do your stuff here
            findViewById(R.id.progressBar).setVisibility(View.GONE);
        }
    });
}




class CustomChromeClient extends WebChromeClient {


    @Override
    public boolean onCreateWindow(WebView view, boolean isDialog,
                                  boolean isUserGesture, Message resultMsg) {
        webViewPopUp = new WebView(globalContext);
        webViewPopUp.setVerticalScrollBarEnabled(false);
        webViewPopUp.setHorizontalScrollBarEnabled(false);
        webViewPopUp.setWebChromeClient(new CustomChromeClient());
        webViewPopUp.getSettings().setJavaScriptEnabled(true);
        webViewPopUp.getSettings().setSaveFormData(true);
        webViewPopUp.getSettings().setEnableSmoothTransition(true);
        webViewPopUp.getSettings().setUserAgentString(userAgent + "yourAppName");

        // pop the  webview with alert dialog
        builder = new AlertDialog.Builder(WebViewActivity.this).create();
        builder.setTitle("");
        builder.setView(webViewPopUp);

        builder.setButton("Close", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                webViewPopUp.destroy();
                dialog.dismiss();
            }
        });

        builder.show();
        builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if(android.os.Build.VERSION.SDK_INT >= 21) {
            cookieManager.setAcceptThirdPartyCookies(webViewPopUp, true);
            cookieManager.setAcceptThirdPartyCookies(webView, true);
        }

        WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
        transport.setWebView(webViewPopUp);
        resultMsg.sendToTarget();

        return true;
    }

    @Override
    public void onCloseWindow(WebView window) {
        //Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
        try {
            webViewPopUp.destroy();
        } catch (Exception e) {
            Log.d("Destroyed with Error ", e.getStackTrace().toString());
        }

        try {
            builder.dismiss();
        } catch (Exception e) {
            Log.d("Dismissed with Error: ", e.getStackTrace().toString());
        }

    }
}

@Override
public void onBackPressed() {
    if (webView!=null){
        if (webView.canGoBack()){
            webView.goBack();
            return;
        }
    }
    super.onBackPressed();
}

}

sum20156
  • 489
  • 1
  • 5
  • 17
  • swift version available ? – Muhammad Asyraf Sep 01 '21 at 17:36
  • thanks for share this working things.... But when i add this code my apps takes almost 2 to min time to load going my web page.....can you tell me how can i fix this issue ? – Jahadul Rakib Jan 19 '22 at 15:10
  • Your answer still work like a charm! Thanks! But.. how can i specify to open it only for login button? For now any link on my website in webview is opened in popup.. Thanks for any feedback ! – Dan Rais Feb 19 '22 at 16:44
  • I wantn't recommend to use an application context for this, but in general it's the great solution, thanks – Hitrene Apr 28 '22 at 15:44
7

Late answer but may help somebody in future.

Actually Google Blocks OAuth Requests Made Via Embedded Browsers. so you can write something like in your code:

 public static final String USER_AGENT = "Mozilla/5.0 (Linux; Android 4.1.1; Galaxy Nexus Build/JRO03C) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19";
 mWebView.getSettings().setUserAgentString(USER_AGENT);

or you can do like this:

mWebView.getSettings().setUserAgentString("yourAppName");

and you should be able to use sign in with google.

Mahmood Hussain
  • 168
  • 2
  • 13
-4

If you use firebase for your application. I think you can find a workaround here: https://firebase.google.com/docs/auth/android/google-signin

Good luck!

Tin Tran
  • 9
  • 1