问题
Can I load a local HTML file (with images and ...) into a WebView
?
Just setting the Source
parameter does not do the trick.
回答1:
You can load it from a file as long as the file is part of the app package, e.g.:
WebView2.Source = new Uri("ms-appx-web:///assets/text.html");
From WebView.Navigate
WebView can load content from the application’s package using ms-appx-web://, from the network using http/https, or from a string using NavigateToString. It cannot load content from the application’s data storage. To access the intranet, the corresponding capability must be turned on in the application manifest.
For a 'random' file, I suppose you could prompt user via file picker to select the file then read it into a string and use NavigateToString, but the user experience there may be a bit odd depending on what you're trying to accomplish.
回答2:
I was working at this problem for a long time and I found a way to do that:
At first you should save it in InstalledLocation
folder. If you haven't option to create a new .html file you can just use file.CopyAsync(htmlFolder, fname + ".html");
Look into my example:
StorageFolder htmlFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.CreateFolderAsync(@"HtmlFiles", CreationCollisionOption.GenerateUniqueName);
IStorageFile file = await htmlFolder .CreateFileAsync(fname + ".html", CreationCollisionOption.GenerateUniqueName);
and than you can easily open your .html file:
var fop = new FileOpenPicker();
fop.FileTypeFilter.Add(".html");
var file = await fop.PickSingleFileAsync();
if (file != null)
{
string myPath = file.Path.Substring(file.Path.IndexOf("HtmlFiles"));
myWebview.Navigate(new Uri("ms-appx-web:///" + myPath));
}
Remember just only from InstalledLocation
you can open it with ms-appx-web:///
来源:https://stackoverflow.com/questions/13225796/load-local-html-into-webview