【问题标题】:Webview2 ExecuteScriptAsync to click an Input buttonWebview2 ExecuteScriptAsync 单击输入按钮
【发布时间】:2023-04-09 08:22:01
【问题描述】:

请看下面这段html代码来理解:

<input type="submit" name="send" class="button" value="Send" onclick="return ussd_send()">
<input type="submit" name="send" class="button" value="Disconnect" onclick="return ussd_exit()">

我想点击Send按钮,但是我使用的代码没有任何效果:

webView21.ExecuteScriptAsync("document.getElementsByClassName('return ussd_send()').click();");

【问题讨论】:

  • return ussd_send() 不是 INPUT 元素的className,而是button。可以使用 TAG 名称和value 属性将其单出来。
  • 你能给我完整的代码吗?下面我也在尝试但不工作! webView21.ExecuteScriptAsync("document.getElementByName('send').click();");
  • 实际上是getElementsByName,它将返回所有具有该名称的元素(这里是两个)。要返回第一个,您可以在其后添加[0],如下所示:webView21.ExecuteScriptAsync("document.getElementsByName('send')[0].click();");
  • 谢谢它的工作哇!!!

标签: c# winforms webview2 execute-script


【解决方案1】:
webView21.ExecuteScriptAsync("document.getElementsByName('send')[0].click();");

这对我的问题有用,这给了我答案 poul bak。

Poul Bak 好人,如果您遇到此问题,您可以将其用于您的目的。

【讨论】:

    【解决方案2】:

    您可以使用Document.querySelectorAll() 找到您的按钮。
    它使用标准CSS Attribute selector 作为输入:

    string inputButtonValue = "Send";
    // Or string inputButtonValue = "Disconnect";
    var func = $"document.querySelectorAll('input[value=\"{inputButtonValue}\"]')[0].click();";
    var result = await webView21.CoreWebView2.ExecuteScriptAsync(func);
    

    兼容的替代方法是循环 Document.getElementsByTagName() 的结果,它返回 HTML 元素的集合:

    string inputButtonValue = "Send";
    var func = "var elms = document.getElementsByTagName('INPUT'); " +
        "for (var i = 0; i < elms.length; i++) {" +
            $"if (elms[i].value == '{inputButtonValue}') {{ " +
                "elms[i].click(); break;" +
            "};" +
        "};";
    
    var result = await webView21.CoreWebView2.ExecuteScriptAsync(func);
    

    您也可以使用WebView2.ExecuteScriptAsync() 代替CoreWebView2.ExecuteScriptAsync(),但前者与WinForms 绑定,后者不绑定。万一在某些时候可移植性可能是个问题。
    您应该等待这些方法,如此处所示,(因为它们都是异步的),但如果您不需要评估 result,这并不是绝对必要的。

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 2021-12-30
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2018-01-13
      相关资源
      最近更新 更多