WinUI3中如何获取WebView2的HTML内容实际高度?
解决WinUI3 WebView2自动适配内容高度的问题
核心问题分析
你拿到的1040固定高度是WebView2默认的初始视口高度,并非内容的实际高度。问题出在未等待内容完全渲染就执行高度计算,加上浏览器默认样式可能干扰结果,导致获取到错误值。
具体实现步骤
1. 标准化HTML结构并重置默认样式
不管服务器返回的HTML有没有html/body标签,都用标准结构包裹,并清除浏览器默认的边距样式,避免影响高度计算:
<html> <head> <style> body { margin: 0; padding: 0; } /* 可在此添加内容需要的自定义样式 */ </style> </head> <body> <!-- 插入服务器返回的HTML内容 --> </body> </html>
2. 等待内容完全渲染后计算高度
不要在WebView2刚完成导航就执行JS,要等页面所有资源加载、元素渲染完成后再获取高度。通过NavigationCompleted事件配合JS的load事件实现:
// 假设WebView2控件名为webView webView.NavigationCompleted += async (sender, args) => { if (args.IsSuccess) { // 等待页面完全加载后,计算真实内容高度 var getHeightScript = @" new Promise(resolve => { if (document.readyState === 'complete') { resolve(Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight )); } else { window.addEventListener('load', () => { resolve(Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight )); }); } })"; var heightResult = await webView.CoreWebView2.ExecuteScriptAsync(getHeightScript); if (double.TryParse(heightResult.Replace("\"", ""), out double realHeight)) { // 将WebView2高度设置为内容真实高度 webView.Height = realHeight; } } };
3. 处理动态内容的高度更新
如果内容包含异步加载的元素(比如图片、动态生成的DOM),需要监听内容变化实时更新高度:
// 注入到页面的脚本,监听内容尺寸变化 window.addEventListener('resize', () => { const currentHeight = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ); // 通过WebMessage把高度传给WinUI3端 window.chrome.webview.postMessage({ type: 'updateHeight', value: currentHeight }); });
然后在WinUI3端接收消息并更新:
webView.CoreWebView2.WebMessageReceived += (sender, args) => { var messageJson = args.WebMessageAsJson; // 解析JSON(示例用System.Text.Json) var heightMsg = System.Text.Json.JsonSerializer.Deserialize<HeightUpdateMessage>(messageJson); if (heightMsg?.Type == "updateHeight") { webView.Height = heightMsg.Value; } }; // 对应的消息模型类 public class HeightUpdateMessage { public string Type { get; set; } public double Value { get; set; } }
关键注意事项
- 必须等待渲染完成:WebView2的
NavigationCompleted仅表示HTML文档加载完毕,图片、动态脚本等资源可能还在加载,所以要依赖load事件确保所有元素渲染完成。 - 多维度计算高度:同时取多种高度属性的最大值,兼容不同的浏览器渲染逻辑。
- 初始高度保持0:不要给WebView2设置固定初始高度,等获取到真实高度后再赋值,避免限制内容渲染。
内容的提问来源于stack exchange,提问作者Thomas KiTe Trentin
相关产品推荐
相关产品推荐

