【问题标题】:Display local html page in UWP WebView在 UWP WebView 中显示本地 html 页面
【发布时间】:2021-01-25 06:06:39
【问题描述】:

我想在 WebView 中显示我的本地 html 页面。如果我将我的 html 页面放在应用程序的本地文件夹中,那么我可以使用以下代码指向它并且它可以工作:

webView.Navigate(new Uri("ms-appdata:///local/myHtmlPage.html"));

但我想知道是否有一个等效的 Uri 可以将我带到发布者缓存文件夹?我问的原因是我想在我部署的应用程序之间共享 html 页面及其数据(文件)。我尝试将 html 页面放在发布者缓存文件夹中,然后将 WebView 的 Navigate 方法指向 html 页面的路径,但我无法让 WebView 打开页面。我收到了一些 HRESULT 异常,但没有详细说明它失败的原因。

我想在不提示用户选择的情况下打开 html 页面中的文件,而我知道如何做到这一点的唯一方法是文件位于页面目录的子目录中。我将有一个使用路径打开文件的 javascript 函数,我将从我的 UWP 应用程序中调用此函数并将文件名传递给它。

在这方面的帮助将不胜感激。

【问题讨论】:

    标签: javascript c# html uwp-xaml


    【解决方案1】:

    在 UWP WebView 中显示本地 html 页面

    当然,您可以使用StreamUriWinRTResolver 将发布者文件夹中的 html 文件转换为流式传输。并使用 WebView NavigateToLocalStreamUri 加载该流。

    例如

    public sealed class StreamUriWinRTResolver : IUriToStreamResolver
    {
        /// <summary>
        /// The entry point for resolving a Uri to a stream.
        /// </summary>
        /// <param name="uri"></param>
        /// <returns></returns>
        public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
        {
            if (uri == null)
            {
                throw new Exception();
            }
            string path = uri.AbsolutePath;
            // Because of the signature of this method, it can't use await, so we
            // call into a separate helper method that can use the C# await pattern.
            return getContent(path).AsAsyncOperation();
        }
    
        /// <summary>
        /// Helper that maps the path to package content and resolves the Uri
        /// Uses the C# await pattern to coordinate async operations
        /// </summary>
        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
            {
                var filename = path.Remove(0, 1);
    
                StorageFile f = await ApplicationData.Current.GetPublisherCacheFolder("Folder1").GetFileAsync(filename);
                IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
                return stream.GetInputStreamAt(0);
            }
            catch (Exception e)
            {
    
    
                throw new Exception("Invalid path");
    
            }
        }
    }
    

    用法

    Uri url = MyWebView.BuildLocalStreamUri("MyTag", "ContentPage.html");
    StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
    MyWebView.NavigateToLocalStreamUri(url, myResolver);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 2018-02-24
      相关资源
      最近更新 更多