Christian
Christian

Reputation: 26387

How can I modify a WebView in Xamarin.Forms to open links in a browser on the device?

By default links (<href..>) Xamarin.Forms WebViews open inside the WebView. Especially in iOS where there's no native backbutton that behavior is unconveniend when opening an Url from the internet.

How do I get Xamarin.Forms to let a browser on the device open the links instead, so that it works in at least Android, iOS and UWP?

Upvotes: 3

Views: 6876

Answers (1)

Gerald Versluis
Gerald Versluis

Reputation: 34013

There is no built-in property or anything that lets you do this.

However, the WebView does have a Navigating event handler. You should be able to hook into that, redirect the user to whatever you want and then cancel the original event. Something like this:

public void WebView_Navigating(object sender, WebNavigatingEventArgs args)
{
    if (args.Url.StartsWith("file://"))
    {
        return;
    }

    Device.OpenUri(new Uri(args.Url));

    args.Cancel = true;
}

To hook it up from code:

var webView = new WebView();
webView.Navigating += WebView_Navigating;

from XAML:

<WebView Navigating="WebView_Navigating" />

More info:

https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.webview.navigating?view=xamarin-forms

Upvotes: 17

Related Questions