diff --git a/src/Core/src/Platform/Windows/MauiWebView.cs b/src/Core/src/Platform/Windows/MauiWebView.cs index 2880166c15d91..d7217174251d9 100644 --- a/src/Core/src/Platform/Windows/MauiWebView.cs +++ b/src/Core/src/Platform/Windows/MauiWebView.cs @@ -2,6 +2,8 @@ using System.Diagnostics; using System.Text.RegularExpressions; using Microsoft.UI.Xaml.Controls; +using Windows.ApplicationModel; +using Windows.Storage; namespace Microsoft.Maui.Platform { @@ -9,7 +11,9 @@ public class MauiWebView : WebView2, IWebViewDelegate { WebView2? _internalWebView; - const string LocalScheme = "ms-appx-web:///"; + // Arbitrary local host name for virtual folder mapping + const string LocalHostName = "appxpackage"; + const string LocalScheme = $"https://{LocalHostName}/"; // Script to insert a tag into an HTML document const string BaseInsertionScript = @" @@ -21,9 +25,12 @@ public class MauiWebView : WebView2, IWebViewDelegate public async void LoadHtml(string? html, string? baseUrl) { + var mapAppxFolder = false; + if (string.IsNullOrEmpty(baseUrl)) { baseUrl = LocalScheme; + mapAppxFolder = true; } // Generate a base tag for the document @@ -36,7 +43,7 @@ public async void LoadHtml(string? html, string? baseUrl) _internalWebView = new WebView2(); // TODO: For now, the CoreWebView2 won't be created without either setting Source or - // calling EnsureCoreWebView2Async(). + // calling EnsureCoreWebView2Async(). await _internalWebView.EnsureCoreWebView2Async(); // When the 'navigation' to the original HTML string is done, we can modify it to include our tag @@ -55,6 +62,16 @@ public async void LoadHtml(string? html, string? baseUrl) await EnsureCoreWebView2Async(); + if (mapAppxFolder) + { + var appxFolder = Package.Current.InstalledLocation.Path; + + CoreWebView2.SetVirtualHostNameToFolderMapping( + LocalHostName, + appxFolder, + Web.WebView2.Core.CoreWebView2HostResourceAccessKind.Allow); + } + // Set the HTML for the 'real' WebView to the updated HTML NavigateToString(!string.IsNullOrEmpty(htmlWithBaseTag) ? htmlWithBaseTag : html); @@ -66,12 +83,21 @@ public async void LoadHtml(string? html, string? baseUrl) _internalWebView.NavigateToString(html); } - public void LoadUrl(string? url) + public async void LoadUrl(string? url) { Uri uri = new Uri(url ?? string.Empty, UriKind.RelativeOrAbsolute); if (!uri.IsAbsoluteUri) { + await EnsureCoreWebView2Async(); + + var appxFolder = Package.Current.InstalledLocation.Path; + + CoreWebView2.SetVirtualHostNameToFolderMapping( + LocalHostName, + appxFolder, + Web.WebView2.Core.CoreWebView2HostResourceAccessKind.Allow); + uri = new Uri(LocalScheme + url, UriKind.RelativeOrAbsolute); }