好的,我想出了一个解决方案:
我将此字符串注入到我的 html 中:
string injectionStyleAndScript = @"html,body {margin: 0;padding: 0;height: 100%;}function getHeight() { var height = document.getElementById('wrapper').offsetHeight; window.external.notify (''+高度);}";
也就是说在之前插入
htmlFragment – this is HTMl that i had to place on my WebView.
htmlFragment = htmlFragment.Insert(htmlFragment.IndexOf("</HEAD>"),injectionStyleAndScript); // Inser the Injection
接下来,计算身体内部,我把它包起来
查找从和到的索引:
int from = htmlFragment.IndexOf("<BODY>")+6;
int to = htmlFragment.IndexOf("</BODY>");
接下来将包裹内的所有内容放入 .
string bodyWrapper = string.Format("<div id='wrapper'>{0}</div>", htmlFragment.Substring(from, (htmlFragment.Length - 1 - from)-(htmlFragment.Length - 1 - to)));
接下来,将旧内容替换为新内容(我们在包装器中创建的内容):
//Cut out the old one
htmlFragment = htmlFragment.Remove(from, (htmlFragment.Length - 1 - from) - (htmlFragment.Length - 1 - to));
//Insert our wrapper
htmlFragment = htmlFragment.Insert(from, bodyWrapper);
//Navigate to the HTML
MyWebView.NavigateToString(htmlFragment);
接下来我们需要将 2 个事件附加到 WebView - DOMContentLoaded и ScriptNotify:
MyWebView.ScriptNotify += MyWebView;
MyWebView.DOMContentLoaded += MyWebView;
MyWebView.NavigateToString(htmlFragment);
这是两个事件处理程序:
void MyWebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
MyWebView.InvokeScriptAsync("getHeight", null);
}
void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
{
string result = e.Value.ToString();
MyWebView.Height = double.Parse(result);
}