You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebView2导航完成后通过JavaScript获取内容高度返回错误值的问题咨询

WebView2导航完成后通过JavaScript获取内容高度返回错误值的问题咨询

问题描述

我目前在WebView2导航完成后,通过JavaScript获取页面内容高度来调整控件尺寸,但遇到了内容高度返回错误的问题。我的初始实现代码如下:

string script = "setTimeout(wait, 10); function wait() {}; var height = document.getElementById('content').offsetHeight.toString(); console.log('Height = ' + height); eval(height);";

var heightString = await webView.ExecuteScriptAsync(script);

if (int.TryParse(heightString, out int height))
{
    int h = (int)((float)height);
    int w = ScreenFramework.getPanelContentWidthWithPadding();
    if(position == POSITION_MENU)
    {
        w = ApplicationFramework.MENU_WIDTH - ApplicationFramework.PADDING;
    }
    webView.MinimumSize = new Size(w, 0);
    webView.MaximumSize = new Size(w, h + 2 * ApplicationFramework.MARGIN);
    webView.Size = new Size(w, h + 2 * ApplicationFramework.MARGIN);
}

当页面内容稍长时,这段代码返回的高度值经常比实际内容高度小,只有连续调用两次才能得到正确的高度。我想知道是WebView2控件本身存在问题,还是我的实现逻辑有疏漏?我期望能一次性获取到准确的内容高度,不需要重复调用。

尝试的解决方法(编辑补充)

我找到了一个新的实现思路,目前测试看起来能正常工作,还需要进一步验证:

首先在导航完成后,通过JavaScript发送就绪消息:

string script = "window.chrome.webview.postMessage(\"ready\");";

WebView.NavigationCompleted += (sender, e) => { WebView.ExecuteScriptAsync(script); WebView.WebMessageReceived += readyReceived; };

然后监听Web消息接收事件,在收到就绪通知后再执行高度设置逻辑:

public void readyReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
{
    try
    {
        string t = e.TryGetWebMessageAsString();
        if (t == "ready")
        {
            setWebViewHeight(WebView, Position);
            WebView.Visible = true;
        }
    } catch { }
}

备注:内容来源于stack exchange,提问作者Dzio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 07:08:04