WebView2 - Get an attribute

Viewed 4385

I am trying to understand the architecture in WebView2. With WebBrowser i used to get an attribute from a result returned by the GetElementById as follows: Document.GetElementById("DropDownList").GetAttribute("selectedIndex")

I know that the ExecuteScriptAsync in WebView2 can run a javascript and return a result as a string. However, it looks like that it does not know how to get an attribute from an element. The below code returns a null. Although, the getElementById returns the correct result.
ExecuteScriptAsync("document.getElementById('DropDownList').getAttribute('selectedIndex')")

Is my syntax incorrect? How to get an attribute in WebView2?. Do we have to write a function in the script and call it from the host?

Thanks

2 Answers

A HTMLSelectElement does not have an attribute called.'selectedIndex'. It has a PROPERTY called 'selectedIndex'.

Call it like this from WebView2:

await ExecuteScriptAsync("document.getElementById('DropDownList').selectedIndex");

You need to await this method. see the reference

string res = await ExecuteScriptAsync("document.getElementById('DropDownList').getAttribute('selectedIndex')")
Related