C# - Xamarin Forms: WebView with navigation to Browser

By , 3/10/2016
(0 ratings)
If you use a WebView in your app, you are in danger to navigate to pages you do not like to navigate to. This Control provides the ability to check if the requested URL is allowed via a regex and opens the default browser in case you do not like to navigate to the page.

Required Namespaces
System
System.Text.RegularExpressions
Xamarin.Forms

Tipp: To instantiate the regex in XAML, have a look at:
http://dotnet-snippets.com/snippet/xamarin-forms-create-regex-instance-in-xaml/10811
Translate to VB
/// <summary>
/// Provides an <see cref="WebView"/> element, which opens the default browser in case the control should navigate to a URL that does not match a regex.
/// </summary>
public class NoExternWebView : WebView
{
    /// <summary>
    /// Creates a new instance of <see cref="NoExternWebView"/> class.
    /// </summary>
    public NoExternWebView()
    {
        this.Navigating += this.OnWebViewNavigating;
    }

    /// <summary>
    /// Identifies the <see cref="AllowedUrlRegex"/> property.
    /// </summary>
    public static readonly BindableProperty AllowedUrlRegexProperty = BindableProperty.Create<NoExternWebView, Regex>(p => p.AllowedUrlRegex, null);

    /// <summary>
    /// Gets or sets the regex for check the URL.
    /// </summary>
    public Regex AllowedUrlRegex
    {
        get { return (Regex)this.GetValue(AllowedUrlRegexProperty); }
        set { this.SetValue(AllowedUrlRegexProperty, value); }
    }

    private void OnWebViewNavigating(object sender, WebNavigatingEventArgs e)
    {
        if (e.Url == null
            || this.AllowedUrlRegex == null
            || this.AllowedUrlRegex.Match(e.Url).Success) return;

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

        e.Cancel = true;
    }
}

Comments

 

Log in, to comment!