1
votes

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
You JavaScript never worked with Webbrowser either. -1 from me. - darbid
@darbid: Actually in the old WebBrowser, you used C# to access the dom, not javascript (the code shown is C#). - Poul Bak
I was referring to this “Although, the getElementById returns the correct result.” - darbid

2 Answers

3
votes

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");
0
votes

You need to await this method. see the reference

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