Skip to content

Commit

Permalink
Fix for dotnet#5523 MauiWebView not loading local files on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
conbre committed Jun 1, 2022
1 parent dfc8f4d commit 08e3d62
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/Core/src/Platform/Windows/MauiWebView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@
using System.Diagnostics;
using System.Text.RegularExpressions;
using Microsoft.UI.Xaml.Controls;
using Windows.ApplicationModel;
using Windows.Storage;

namespace Microsoft.Maui.Platform
{
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 <base> tag into an HTML document
const string BaseInsertionScript = @"
Expand All @@ -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
Expand All @@ -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 <base> tag
Expand All @@ -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);

Expand All @@ -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);
}

Expand Down

0 comments on commit 08e3d62

Please sign in to comment.