I’m facing an issue with loading a local HTML file into the WebView of my MAUI Windows app. While I can successfully load the HTML file from a ContentPage. But I want to achieve this functionality using a custom renderer in Windows. However, I’ve encountered a problem where the local HTML file fails to load, and attempts to load URLs are also unsuccessful when using the custom renderer. Notably, there are no error messages provided to indicate the source of the issue
using Microsoft.Maui.Controls.Handlers.Compatibility;
using Microsoft.Maui.Controls.Platform;
using Microsoft.Maui.Controls.PlatformConfiguration.WindowsSpecific;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Web.WebView2.Core;
using WebView = Microsoft.Maui.Controls.WebView;
using WWebView = Microsoft.UI.Xaml.Controls.WebView2;
public class WindowsWebViewRenderer : ViewRenderer<WebView, WWebView>
{
WWebView _webView;
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (Control == null)
{
_webView = new WebView2();
Connect(_webView);
SetNativeControl(_webView);
}
if (e.NewElement != null)
{
LoadHtml();
}
}
void Connect(WWebView webView)
{
if (webView == null)
{
return;
}
webView.CoreProcessFailed += OnCoreProcessFailed;
webView.WebMessageReceived += OnWebMessageReceived;
webView.NavigationStarting += OnNavigationStarted;
webView.NavigationCompleted += OnNavigationCompleted;
}
async void LoadHtml()
{
try
{
if (_webView != null)
{
_webView.Source = new Uri("https://www.google.lk");
}
/* using var stream = await FileSystem.OpenAppPackageFileAsync("HTMLPage.html");
using var reader = new StreamReader(stream);
var htmlContent = reader.ReadToEnd();
if (_webView != null)
{
await _webView.EnsureCoreWebView2Async();
var core_wv2 = _webView.CoreWebView2;
if (core_wv2 != null)
{
core_wv2.NavigateToString(htmlContent);
}
}*/
}
catch (Exception ex)
{
Console.WriteLine($"Error loading HTML file: {ex.Message}");
}
}
}
Registered the handler also
.ConfigureMauiHandlers((handlers) =>
{
handlers.AddHandler(typeof(WebView), typeof(MauiAppOne.Platforms.Windows.Renderers.WindowsWebViewRenderer));
});