Monday, September 11, 2017

WebView blank in Xamarin Forms on UWP

TLDR;

If you are hooking up events for a Xamarin Forms WebView, wrap the hooking up in a Device.BeginInvokeOnMainThread if you experience a blank WebView. I've seen this issue mostly on UWP.

    public MyView()
    {
        this.InitializeComponent();
       
        Device.BeginInvokeOnMainThread(() =>
        {
            // Hook up events in here
            this.myWebView.Navigating += async (s, e) =>
            {
                // Do stuff here
            };
        });
    }

Longer version

I have a login view in my app and the code looks like this.

    public partial class LoginView : ContentPage
    {
        public LoginView(LoginViewModel vm)
        {
            this.InitializeComponent();
            this.BindingContext = vm;

            this.LoginWebView.Navigating += async (s, e) =>
            {
                this.BusyLabel.IsVisible = true;
                await vm?.Navigating(e.Url);
            };

            this.LoginWebView.Navigated += async (s, e) =>
            {
            
                this.BusyLabel.IsVisible = false;
            };
  
        }
    }

I needed to hook up the Navigating and Navigated events for two reasons;
  1. To display a busy/loading label over the webview
  2. To pass the resulting URL back to the ViewModel
This works... Most of the time. But sometimes the WebView just displays a white square. I tried a bunch of different urls trying to determine if it was something in the html that was messing something up. 

Then I read this post (https://forums.xamarin.com/discussion/63280/xamarin-forms-webview-does-not-work-once-the-navigating-eventhandler-is-setup). It wasn't really about this issue but the title of the post made me think.

Perhaps, if I delay the event hooking-uping it might magically work again. 

So I wrapped the hookups in a Device.BeginInvokeOnMainThread(...) call and it just seems to work.

An other related issue you might experience is this. But this goes for all controls, not only WebView.
  • https://stackoverflow.com/questions/34330446/xamarin-forms-webview-not-showing-up


1 comment: