uwp WebView navigation NavigateToLocalStreamUri


Example

In case when NavigateToString can't handle some content, use NavigateToLocalStreamUri method. It will force every locally-referenced URI inside the HTML page to call to the special resolver class, which can provide right content on the fly.

Assets/Html/html-sample.html file:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML document</title>
    </head>
    <body>
        <p>This is simple HTML content.</p>
        <img src="cat.jpg"/>
    </body>
</html>

Code:

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);
    }
}

This code will take HTML page from app package and embed content from local folder into it. Provided that you have image "cat.jpg" in /local/content folder, it will show HTML page with cat image.