1

Please see below this html code for understand:

<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()">

I want to click the Send Button, but the code I'm using doesn't have any effect:

webView21.ExecuteScriptAsync("document.getElementsByClassName('return ussd_send()').click();");
Jimi
  • 29,621
  • 8
  • 43
  • 61
micheline
  • 61
  • 1
  • 7
  • `return ussd_send()` is not the INPUT element's `className`, that's `button`. The TAG name and `value` Attribute can be used to single it out. – Jimi Aug 02 '21 at 15:15
  • can you give me full code how I am doing? below I am trying too but not working!! webView21.ExecuteScriptAsync("document.getElementByName('send').click();"); – micheline Aug 02 '21 at 17:04
  • It's actually `getElementsByName` which will return all elements with that name (here two). to return the first you can add `[0]` after it, like this: `webView21.ExecuteScriptAsync("document.getElementsByName('send')[0].click();");`. – Poul Bak Aug 03 '21 at 07:52
  • 1
    Thanks it's working wow!!! – micheline Aug 03 '21 at 15:46

2 Answers2

4
webView21.ExecuteScriptAsync("document.getElementsByName('send')[0].click();");

This working for my problem & this give me answer poul bak.

Poul Bak good man & you can use for your purpose like this issue if you face.

micheline
  • 61
  • 1
  • 7
1

You can find your Button using Document.querySelectorAll().
It uses a standard CSS Attribute selector as input:

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

The compatible alternative is to loop the result of Document.getElementsByTagName(), which returns a collection of HTML elements:

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);

You can also use WebView2.ExecuteScriptAsync() instead of CoreWebView2.ExecuteScriptAsync(), but the former is tied to WinForms, the latter is not. In case portability could be an issue at some point.
You should await those methods, as shown here, (since both are async), but it's not stricly necessary in case you don't need to evaluate result.

Jimi
  • 29,621
  • 8
  • 43
  • 61