【问题标题】:NavigateToLocalStreamUri not called for resourcesNavigateToLocalStreamUri 未调用资源
【发布时间】:2018-06-08 13:30:32
【问题描述】:

我在WebView 中使用NavigateToLocalStreamUri,这样我就可以为浅色和深色主题加载特定的样式表。我像这样格式化我的 HTML 文件:

<!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>

这是我的StreamUriResolver代码如下:

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

并使用以下代码调用它:

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

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

我在UriStreamResolver 中添加了一个断点,但是GetContent 在 HTML 页面上只被命中一次,而不是页面上的样式表或图像。它们已加载并且图像显示正常,但条件样式表未加载。我读过的文章和帖子说每次需要加载资源时都应该调用GetContent,但我没有看到这种行为。

【问题讨论】:

  • 您是否将css 文件放在Content 文件夹中?
  • 是的,所有文件都在Content文件夹中。

标签: c# css webview uwp


【解决方案1】:

经过反复试验,我发现问题在于在我的许多页面中使用了&lt;base&gt; 标签。这导致网页在加载这些资产时不使用解析器。删除 &lt;base&gt; 标记并仅使用相对 URL 现在使用解析器来处理所有需要加载的资产。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2019-07-26
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多