0

I am using NavigateToLocalStreamUri in WebView so that I can load specific style sheets for the light and dark themes. I format my HTML files like so:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="css/main.css" />
    <link rel="stylesheet" type="text/css" href="css/theme-(RequestedTheme).css" />
</head>
<body>
...
</body>
</html>

Here is my StreamUriResolver code is as follows:

public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
{
    if (uri == null)
    {
        throw new ArgumentException("Uri cannot be empty");
    }
    string path = uri.AbsolutePath;
    // Because of the signature of the this method, it can't use await, so we 
    // call into a seperate helper method that can use the C# await pattern.
    return GetContent(path).AsAsyncOperation();
}

private async Task<IInputStream> GetContent(string path)
{
    // We use a package folder as the source, but the same principle should apply
    // when supplying content from other locations
    try
    {
        // Replace content modifiers with actual values
        path = path.Replace("(RequestedTheme)", Application.Current.RequestedTheme.ToString().ToLowerInvariant());
        Uri localUri = new Uri("ms-appx:///Content" + path);
        StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
        IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
        return stream.GetInputStreamAt(0);
    }
    catch (Exception) { throw new InvalidOperationException("Invalid path"); }
}

And it is called with this code:

Uri uri = webViewer.BuildLocalStreamUri("Landing", url);
StreamUriResolver myResolver = new StreamUriResolver();

// Pass the resolver object to the navigate call.
webViewer.NavigateToLocalStreamUri(uri, myResolver);

I added a breakpoint in the UriStreamResolver, but GetContent is only hit once on the HTML page, and not for the style sheets or images on the page. They are loaded and the image shows fine, but the conditional style sheet does not load. The articles and posts I've read say that GetContent should be called every time a resource needs to be loaded, but I am not seeing this behavior.

Ramsay Smith
  • 1,098
  • 13
  • 30

1 Answers1

1

After some trial and error, I discovered that the issue was the use of the <base> tag in a number of my pages. This caused the webpage to not use the resolver when loading those assets. Removing the <base> tag and using only relative URLs now uses the resolver for all the assets that need to be loaded.

Ramsay Smith
  • 1,098
  • 13
  • 30