NavigateToLocalStreamUri
如果 NavigateToString 無法處理某些內容,請使用 NavigateToLocalStreamUri 方法。它將強制 HTML 頁面內的每個本地引用的 URI 呼叫特殊的解析器類,它可以動態提供正確的內容。
Assets / Html / html-sample.html 檔案:
<!DOCTYPE html>
<html>
<head>
<title>HTML document</title>
</head>
<body>
<p>This is simple HTML content.</p>
<img src="cat.jpg"/>
</body>
</html>
碼:
protected override void OnNavigatedTo(NavigationEventArgs args)
{
// The Uri resolver takes is in the form of "ms-local-stream://appname_KEY/folder/file"
// For simplicity, there is method BuildLocalStreamUri which returns correct Uri.
var uri = this.webView.BuildLocalStreamUri("SomeTag", "/html-sample.html");
var resolver = new StreamUriResolver();
this.webView.NavigateToLocalStreamUri(uri, resolver);
base.OnNavigatedTo(args);
}
public sealed class StreamUriResolver : IUriToStreamResolver
{
public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
var path = uri.AbsolutePath;
return GetContent(path).AsAsyncOperation();
}
private async Task<IInputStream> GetContent(string uriPath)
{
Uri localUri;
if (Path.GetExtension(uriPath).Equals(".html"))
{
localUri = new Uri("ms-appx:///Assets/Html" + uriPath);
}
else
{
localUri = new Uri("ms-appdata:///local/content" + uriPath);
}
var file = await StorageFile.GetFileFromApplicationUriAsync(localUri);
var stream = await file.OpenAsync(FileAccessMode.Read);
return stream.GetInputStreamAt(0);
}
}
此程式碼將從應用程式包中獲取 HTML 頁面,並將本地資料夾中的內容嵌入其中。如果你在/ local / content 資料夾中有影象“cat.jpg”,它將顯示帶有貓影象的 HTML 頁面。