Подтвердить что ты не робот

Как изменить размер веб-представления на основе содержимого HTML в Windows 10 UWP?

В настоящее время я работаю над Windows 10 UWP App и сталкиваюсь с проблемой с 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="#" onclick="location.href='http://www.pdf995.com/samples/pdf.pdf'; return false;" 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);
                        }
                    }
                };

Может кто-нибудь предположить, почему я получаю очень большую высоту, даже если контент небольшой?

4b9b3361

Ответ 1

вы можете попытаться проанализировать строку "document.body.scrollHeight.toString()" после загрузки содержимого, чтобы установить новую высоту для вашего веб-просмотра. Вот пример с 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"));
}