【问题标题】:How to resize Webview height based on HTML content in Windows 10 UWP?如何根据 Windows 10 UWP 中的 HTML 内容调整 Webview 高度?
【发布时间】:2017-02-16 17:54:39
【问题描述】:

我目前正在使用 Windows 10 UWP 应用程序并面临 WebView 的问题,即当我的 HTML 内容较少时,我在 javascript 中的高度越来越高。我的代码如下

WebView webView = new WebView() { IsHitTestVisible = true };
                string notifyJS = @"<script type='text/javascript' language='javascript'>

                                            function setupBrowser(){
                                            document.touchmove=function(){return false;};;
                                            document.onmousemove=function(){return false;};
                                            document.onselectstart=function(){return false;};
                                            document.ondragstart=function(){return false;}
                                            window.external.notify('ContentHeight:'+document.body.firstChild.offsetHeight);
                                            //window.external.notify('ContentHeight:'+document.getElementById('pageWrapper').offsetHeight);
                                            var links = document.getElementsByTagName('a');
                                            for(var i=0;i<links.length;i++) {
                                               links[i].onclick = function() {
                                                    window.external.notify(this.href);
                                                        return false;
                                            }
                                            }
                                        }
                                    </script>";


                string htmlContent;
                if (hexcolor != null)
                {
                    htmlContent = string.Format("<html><head>{0}</head>" +
                                                    "<body onLoad=\"setupBrowser()\" style=\"margin:0px;padding:0px;background-color:{2};\">" +
                                                    "<div id=\"pageWrapper\" style=\"width:100%;word-wrap:break-word;padding:0px 25px 0px 25px\">{1}</div></body></html>",
                                                    notifyJS,
                                                    formItem.I_DEFAULT_VALUE,
                                                    hexcolor);
                }

这里 formItem.I_DEFAULT_VALUE 是 HTML without html,head and body tags,其值为

<p>
<span style="font-size: 14px;">To help us investigate your query please can you make a sheet using the following&nbsp;</span><a href="http://www.pdf995.com/samples/pdf.pdf" style="font-size: 14px;" target="_blank">document</a><span style="font-size: 14px;">.</span></p>
<p>
<strong><span style="font-size: 14px;">Testing WebView Height</span></strong></p>

HexColor 是需要应用的背景颜色。

而我的script_notify方法如下:

webView.ScriptNotify += async (sender, e) =>
                {
                    if (e.Value.StartsWith("ContentHeight"))
                    {
                        (sender as WebView).Height = Convert.ToDouble(e.Value.Split(':')[1]);
                        return;
                    }

                    if (!string.IsNullOrEmpty(e.Value))
                    {
                        string href = e.Value.ToLower();
                        if (href.StartsWith("mailto:"))
                        {
                            LauncherOptions options = new LauncherOptions();
                            options.DisplayApplicationPicker = true;
                            options.TreatAsUntrusted = true;
                            var success = await Launcher.LaunchUriAsync(new Uri(e.Value), options);
                        }
                        else if (href.StartsWith("tel:"))
                        {
                            LauncherOptions options = new LauncherOptions();
                            options.DisplayApplicationPicker = true;
                            options.TreatAsUntrusted = true;
                            var success = await Launcher.LaunchUriAsync(new Uri(e.Value), options);
                        }

                        else
                        {
                            LauncherOptions options = new LauncherOptions();
                            options.DisplayApplicationPicker = true;
                            options.TreatAsUntrusted = true;
                            var success = await Launcher.LaunchUriAsync(new Uri(e.Value), options);
                        }
                    }
                };

有人可以建议为什么即使内容很小,我的高度也会变得很大?

【问题讨论】:

  • 我用你的代码做了一个演示,但没有重现你的问题。 webView 的高度已正确调整大小。您能否发布formItem.I_DEFAULT_VALUE 的代码,或者分享一个可以重现此问题的基本演示。我正在使用 WebView.NavigateToString 来呈现 html 内容。
  • @ElvisXia-MSFT 我添加了formItem.I_DEFAULT_VALUE,我也在使用WebView.NavigateToString。另外,我正在使用 C# 而不是 XAML 动态创建 webview
  • @ElvisXia-MSFT 也使用window.external.notify('ContentHeight:'+document.body.firstChild.offsetHeight);
  • 仍然无法复制。你可以在这里试试我的演示:WebViewDynamicHeightSample.
  • :-( 不知道为什么它在我身边不起作用。我将尝试创建演示项目并检查是否可以重现该问题。

标签: javascript c# webview uwp windows-10-universal


【解决方案1】:

您可以在内容加载后尝试解析字符串“document.body.scrollHeight.toString()”,以便为您的 webview 设置新的高度。 这是 NavigationCompleted 的示例,但您可以使用自定义事件

public static class WebViewExtensions  
{
    public static void ResizeToContent(this WebView webView)
    {
        var heightString = webView.InvokeScript("eval", new[] {"document.body.scrollHeight.toString()" });
        int height;
        if (int.TryParse(heightString, out height))
        {
            webView.Height = height;
        }
    }
}

public Page()  
{
    MyWebView.NavigationCompleted += (sender, args) => sender.ResizeToContent();
    MyWebView.Navigate(new Uri("index.html"));
}

【讨论】:

  • 你试过了吗?我过去尝试过类似的方法,但没有成功
  • 去年是的。但我们的需求可能并不完全相同。当你说它不起作用时,document.body.scrollHeight返回的值是否也很大,或者“eval”失败了?
【解决方案2】:

我不确定为什么你得到的值太高,我遇到了一个稍微不同的问题:我得到的文档的高度太小(高度似乎没有考虑图像)。我尝试了多个事件(NavigationFinishedLoadCompleted、...),但在这些事件中我都无法获得准确的高度。

最终对我有用的是等待一小段时间,直到我发回文档的高度。不完全是一个很好的解决方案,我希望我能够在某个时候简化它。也许这也适用于您的问题。

我注入了一个等待 100 毫秒然后将其发回的脚本。即使图像尚未完全加载,内容大小对我来说也是准确的。

window.setTimeout(function () {
    var height = document.body.scrollHeight.toString();
    window.external.notify("ContentHeight:" + height);
}, 100);

【讨论】:

    猜你喜欢
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多