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

WebView2注入JS执行click报错Cannot read properties of undefined排查

问题根因定位

报错由三个核心问题共同导致:

  1. JavaScript代码存在低级笔误:声明的元素集合变量名为Next,实际调用时写的是从未定义的NextLink,直接触发undefined读取错误。
  2. DOM API使用错误:document.getElementsByName()返回值是类数组格式的HTMLCollection节点集合,集合本身没有click方法,直接调用必然报错,必须取下标拿到单个DOM元素才能触发点击。
  3. 脚本执行时机早于DOM渲染:AddScriptToExecuteOnDocumentCreatedAsync的触发时机是文档对象刚创建、页面DOM还未开始解析的阶段,此时执行元素查询逻辑只能拿到空集合,取下标取元素仍然返回undefined。

修复方案

方案1:保留原有注入方式,修正JS逻辑(改动最小)

替换原有Script.js的内容,主动监听DOM加载完成事件后再执行业务逻辑,同时修正变量和API调用错误:

document.addEventListener('DOMContentLoaded', function() {
    const nextElements = document.getElementsByName("next");
    // 双重校验:集合存在,且集合内确实有元素
    if (nextElements && nextElements.length > 0) {
        alert("找到目标元素");
        // 你的HTML结构中name=next的是img标签,本身无跳转行为,实际跳转逻辑在外层a标签上
        const targetLink = nextElements[0].closest('a');
        // 有外层a标签就点a触发跳转,没有就点img本身
        targetLink ? targetLink.click() : nextElements[0].click();
    } else {
        alert("未找到目标元素");
    }
});

C#端原有代码不需要调整即可正常运行。

方案2:调整C#注入时机(更稳妥,适合复杂页面)

把脚本执行时机调整到页面导航完成后,不需要在JS里额外加DOM加载监听:

  1. 保留CoreWebView2InitializationCompleted事件里的初始化逻辑,移除原有的AddScriptToExecuteOnDocumentCreatedAsync调用,新增导航完成事件注册:
    private async void WebView2Control_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
    {
        if (!e.IsSuccess)
        {
            MessageBox.Show($"WebView2创建失败,异常信息:{e.InitializationException}");
            return;
        }
        // 原有事件注册逻辑保留
        this.webView2Control.CoreWebView2.SourceChanged += CoreWebView2_SourceChanged;
        this.webView2Control.CoreWebView2.HistoryChanged += CoreWebView2_HistoryChanged;
        this.webView2Control.CoreWebView2.DocumentTitleChanged += CoreWebView2_DocumentTitleChanged;
        this.webView2Control.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.Image);
        // 新增导航完成事件监听
        this.webView2Control.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
    }
    
  2. 新增导航完成事件处理,在页面全部加载完成后执行脚本:
    private async void CoreWebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
    {
        if (e.IsSuccess)
        {
            string script = File.ReadAllText(@"D:\Vb\Test\WebView2Samples-main\SampleApps\WebView2WindowsFormsBrowser\Script.js");
            await webView2Control.CoreWebView2.ExecuteScriptAsync(script);
        }
    }
    
  3. Script.js里直接写查询和点击逻辑即可,不需要加DOMContentLoaded监听:
    const nextElements = document.getElementsByName("next");
    if (nextElements && nextElements.length > 0) {
        const targetLink = nextElements[0].closest('a');
        targetLink ? targetLink.click() : nextElements[0].click();
    }
    

额外注意点
  • 你提供的示例HTML结构中最后一个img标签的alt属性缺少闭合引号:alt="last image>,部分内核下可能出现DOM解析异常导致元素定位失败,需要补全引号修正。
  • 如果目标网页是前端框架渲染的动态内容,DOMContentLoaded或NavigationCompleted触发时目标元素可能还未生成,这种情况需要加短间隔轮询,或者使用MutationObserver监听DOM变化,等目标元素出现后再执行点击逻辑。

内容的提问来源于stack exchange,提问作者Holly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 19:27:19