UWP WebView Intermittently Fails to Load in a Xamarin.Forms App - Resolved!

As I've previously mentioned I've been porting an existing Xamarin.Forms app over to UWP and tonight I've had to tackle an annoying bug which was quite difficult to overcome and I thought worthwhile sharing.

The bug occurs when loading WebViews with HTML directly rather than a URL. I found that roughly 1 in 5 page loads ended up a blank page being rendered. As this is now the third platform for the App I was fairly confident the html and everything was correct.

First of all I suspected a layout issue and maybe the width/height was being messed up so I added a background colour to the control but this always rendered. So not a layout issue.

A quick Google led me to Johan Karlsson's post on events needing to be added on the main UI Thread this seemed better at first but i ended up still hitting the issue 1 in 10 page loads.  More googling led me to a Xamarin bug with the issue but no resolution :(

Taylor Buchanan comments on the bug with a work around however I found this loaded the HTML every page load but my local Javascript and CSS files were never loaded.
At this point I decided it was time to start seeing what was happening so created a custom renderer for the WebView and wired up every event on the WebView control and logged to the debug window when each event happened to see if there was a pattern. There was :) Whenever the page failed to load the ContentLoading event never fired. It seemed a natural next step to change the custom renderer to detect if the content failed to load and then try and remedy the issue.

I started with scheduling a task to complete after the maximum time I'd want a page to load in and then after this look to see if the content had loaded. If it hadn't refresh the page and see if the content would reload.

Alas, although I was hitting the new code the refresh method didn't work. Next I thought could I instead tweak Taylor's workaround and just reload the HTML after a content failure occurs.
This worked :) The slight stutter when the issue happens is noticeable and i might try and lower the 350ms down to 200ms or so but it now only happens on rare occasions not 1 in 5.
Hope this helps


Popular posts from this blog

WebUSB - An unexpected update...

Can you use BuildRoot with Windows Subsystem for Linux......

DotNet CLI , private NuGet feeds and Linux...