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();");
4
  • 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. Commented Aug 2, 2021 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();"); Commented Aug 2, 2021 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();");. Commented Aug 3, 2021 at 7:52
  • 1
    Thanks it's working wow!!! Commented Aug 3, 2021 at 15:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.