public
static
class
WebView2LargeHtmlExtension
{
/// <summary>
/// htmlTemplate Cache
/// </summary>
static
readonly
Dictionary<
string
,
string
> TemplateCache =
new
Dictionary<
string
,
string
>();
public
static
async
void
NavigateToHtml(
this
WebView2 browser,
string
template)
{
string
key = Guid.NewGuid().ToString();
TemplateCache[key] = template;
browser.Source =
new
Uri($
"https://template/?key={key}"
);
}
public
static
void
RegLargeHtmlHandler(
this
CoreWebView2 cwv2)
{
cwv2.AddWebResourceRequestedFilter(
"https://template/*"
, CoreWebView2WebResourceContext.All);
cwv2.WebResourceRequested += CoreWebView2_WebResourceRequested_LargeHtmlHandler;
}
private
static
async
void
CoreWebView2_WebResourceRequested_LargeHtmlHandler(CoreWebView2 sender, CoreWebView2WebResourceRequestedEventArgs args)
{
string
requestUri = args.Request.Uri;
if
(requestUri.StartsWith(
"https://template/"
))
{
Deferral def = args.GetDeferral();
try
{
Uri uri =
new
Uri(requestUri);
NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(uri.Query);
string
headers = $
"Content-Type: text/html; charset=utf-8"
;
if
(TemplateCache.Remove(queryString[
"key"
],
out
string
html))
{
InMemoryRandomAccessStream ms =
new
InMemoryRandomAccessStream();
using
(
var
dataWriter =
new
DataWriter(ms))
{
dataWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
dataWriter.ByteOrder = ByteOrder.LittleEndian;
dataWriter.WriteString(html);
await
dataWriter.StoreAsync();
await
dataWriter.FlushAsync();
dataWriter.DetachStream();
ms.Seek(0);
}
args.Response = sender.Environment.CreateWebResourceResponse(ms, 200,
"OK"
, headers);
}
}
catch
(Exception)
{
args.Response = sender.Environment.CreateWebResourceResponse(
null
, 404,
"Not found"
,
""
);
}
finally
{
def.Complete();
}
}
}
}
private
async
void
Webview2_CoreWebView2Initialized(WebView2 sender, CoreWebView2InitializedEventArgs args)
{
sender.CoreWebView2.RegLargeHtmlHandler();
}