Xamarin Forms WebView open external link

Viewed 3934

I have a webview inside my application and when an external link is clicked (that in normal browser is open in a new tab), I can't then go back to my website.

It is possible when a new tab is open to have the menu closed that tab like Gmail do ?

enter image description here

The objective is that, whenever a link is clicked, the user would have the choice to choose which option to view the content with, e.g. Clicking a link would suggest open youtube app or google chrome. The purpose is to appear the google chrome option

Or what suggestions do you have to handle this situation ?

1 Answers

If I understood you correctly, you want to have the option to select how to open the web link - inside your app, or within another app's (browser) context.

If this is correct, then you can use Xamarin.Essentials: Browser functionality.

public async Task OpenBrowser(Uri uri)
{
    await Browser.OpenAsync(uri, BrowserLaunchMode.SystemPreferred);
}

Here the important property is the BrowserLaunchMode flag, which you can learn more about here

Basically, you have 2 options - External & SystemPreferred.

  1. The first one is clear, I think - it will open the link in an external browser.
  2. The second options takes advantage of Android's Chrome Custom Tabs & for iOS - SFSafariViewController

P.S. You can also customise the PreferredToolbarColor, TitleMode, etc.

Edit: Based from your feedback in the comments, you want to control how to open href links from your website.

If I understood correctly, you want the first time that you open your site, to not have the nav bar at the top, and after that to have it. Unfortunately, this is not possible.

You can have the opposite behaviour achieved - the first time that you open a website, to have the nav bar and if the user clicks on any link, to open it externally (inside a browser). You have 2 options for this:

  1. To do it from your website - change the a tag's target to be _blank like this;
  2. To do it from your mobile app - create a Custom renderer for the WebView. In the Android project's renderer implementation, change the Control's WebViewClient like so:
    public class CustomWebViewClient : WebViewClient
    {
        public override bool ShouldOverrideUrlLoading(Android.Webkit.WebView view, IWebResourceRequest request)
        {
            Intent intent = new Intent(Intent.ActionView, request.Url);
            CrossCurrentActivity.Current.StartActivity(intent);
            return true;
        }
    }
Related