Search code examples
androidandroid-intentwebviewandroid-webviewback-button

How to open a web browser in WebView app when an external link is clicked?


I want to open external links in web browser using intent and should not open in my WebView app except my internal links starts with "https://www.ecommerce.in/"
I have written code as given below:

@Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) 
 {
  if (!url.contains("https://www.ecommerce.in/")) 
  {
   Uri uri = Uri.parse(url);
   startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
   view.loadUrl(url);
   CookieManager.getInstance().setAcceptCookie(true);
  } else {
          webViewProduct.loadUrl(url);
          return true;
         }
 }    

This code is working perfectly as I want but the problem is when I pressed back button on web browser the same external link is opening in my WebView app.

Please let me know where I'm doing wrong. Thanks in advance.


Solution

  • You should have to remove view.loadUrl(url) from you code , So

    Please replace your code as given below

    @Override
     public boolean shouldOverrideUrlLoading(WebView view, String url) 
     {
      if (!url.contains("https://www.ecommerce.in/")) 
      {
       Uri uri = Uri.parse(url);
       startActivity(Intent.createChooser(new Intent(Intent.ACTION_VIEW, uri), "Choose browser"));
    
       CookieManager.getInstance().setAcceptCookie(true);
      } else {
              webViewProduct.loadUrl(url);
              return true;
             }
     }