2
2
using System . Diagnostics ;
3
3
using System . Text . RegularExpressions ;
4
4
using Microsoft . UI . Xaml . Controls ;
5
+ using Windows . ApplicationModel ;
5
6
6
7
namespace Microsoft . Maui . Platform
7
8
{
8
9
public class MauiWebView : WebView2 , IWebViewDelegate
9
10
{
10
11
WebView2 ? _internalWebView ;
11
12
12
- const string LocalScheme = "ms-appx-web:///" ;
13
+ // Arbitrary local host name for virtual folder mapping
14
+ const string LocalHostName = "appxpackage" ;
15
+ const string LocalScheme = $ "https://{ LocalHostName } /";
13
16
14
17
// Script to insert a <base> tag into an HTML document
15
18
const string BaseInsertionScript = @"
@@ -21,9 +24,12 @@ public class MauiWebView : WebView2, IWebViewDelegate
21
24
22
25
public async void LoadHtml ( string ? html , string ? baseUrl )
23
26
{
27
+ var mapAppxFolder = false ;
28
+
24
29
if ( string . IsNullOrEmpty ( baseUrl ) )
25
30
{
26
31
baseUrl = LocalScheme ;
32
+ mapAppxFolder = true ;
27
33
}
28
34
29
35
// Generate a base tag for the document
@@ -36,7 +42,7 @@ public async void LoadHtml(string? html, string? baseUrl)
36
42
_internalWebView = new WebView2 ( ) ;
37
43
38
44
// TODO: For now, the CoreWebView2 won't be created without either setting Source or
39
- // calling EnsureCoreWebView2Async().
45
+ // calling EnsureCoreWebView2Async().
40
46
await _internalWebView . EnsureCoreWebView2Async ( ) ;
41
47
42
48
// When the 'navigation' to the original HTML string is done, we can modify it to include our <base> tag
@@ -55,6 +61,16 @@ public async void LoadHtml(string? html, string? baseUrl)
55
61
56
62
await EnsureCoreWebView2Async ( ) ;
57
63
64
+ if ( mapAppxFolder )
65
+ {
66
+ var appxFolder = Package . Current . InstalledLocation . Path ;
67
+
68
+ CoreWebView2 . SetVirtualHostNameToFolderMapping (
69
+ LocalHostName ,
70
+ appxFolder ,
71
+ Web . WebView2 . Core . CoreWebView2HostResourceAccessKind . Allow ) ;
72
+ }
73
+
58
74
// Set the HTML for the 'real' WebView to the updated HTML
59
75
NavigateToString ( ! string . IsNullOrEmpty ( htmlWithBaseTag ) ? htmlWithBaseTag : html ) ;
60
76
@@ -66,12 +82,21 @@ public async void LoadHtml(string? html, string? baseUrl)
66
82
_internalWebView . NavigateToString ( html ) ;
67
83
}
68
84
69
- public void LoadUrl ( string ? url )
85
+ public async void LoadUrl ( string ? url )
70
86
{
71
87
Uri uri = new Uri ( url ?? string . Empty , UriKind . RelativeOrAbsolute ) ;
72
88
73
89
if ( ! uri . IsAbsoluteUri )
74
90
{
91
+ await EnsureCoreWebView2Async ( ) ;
92
+
93
+ var appxFolder = Package . Current . InstalledLocation . Path ;
94
+
95
+ CoreWebView2 . SetVirtualHostNameToFolderMapping (
96
+ LocalHostName ,
97
+ appxFolder ,
98
+ Web . WebView2 . Core . CoreWebView2HostResourceAccessKind . Allow ) ;
99
+
75
100
uri = new Uri ( LocalScheme + url , UriKind . RelativeOrAbsolute ) ;
76
101
}
77
102
0 commit comments