Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 649
Christian Avatar asked Nov 25 '25 23:11

Christian


1 Answers

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

like image 60
Gerald Versluis Avatar answered Nov 28 '25 16:11

Gerald Versluis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!