如何在Windows 10 UWP中基于HTML内容调整Webview高度?

我目前正在使用Windows 10 UWP App并面临WebView的问题,当我的HTML内容较少时,我在javascript中获得更多高度。 我的守则如下

WebView webView = new WebView() { IsHitTestVisible = true }; string notifyJS = @" 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; } } } "; string htmlContent; if (hexcolor != null) { htmlContent = string.Format("{0}" + "" + "
{1}
", notifyJS, formItem.I_DEFAULT_VALUE, hexcolor); }

这里的formItem.I_DEFAULT_VALUE是HTML without html,head and body tags ,它的值是

 

To help us investigate your query please can you make a sheet using the following document.

Testing WebView Height

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

有人可以建议为什么即使内容很小我也会变得非常大吗?

您可以尝试在加载内容后解析字符串“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")); }