How do I capture text from a HTML element given its id=”” from a WebView2 in VB.NET?

You have wrong event handler signature here:

Private Async Function WebView2_NavigationCompletedAsync(
                sender As Object, e As CoreWebView2NavigationCompletedEventArgs) _
                As Task Handles WebView21.NavigationCompleted
    ' ...
End Function

an event handler is a Sub/void not a Function and does not return any value of any type.

The correct signature is:

Private Sub WebView2_NavigationCompletedAsync(
                    sender As Object, e As CoreWebView2NavigationCompletedEventArgs) _
                    Handles WebView21.NavigationCompleted
    ' ...
End Sub

As for the webView2 part, make the handle Async method and get the content of the target td as follows:

Private Async Sub WebView2_NavigationCompletedAsync(
                    sender As Object,
                    e As CoreWebView2NavigationCompletedEventArgs) _
                    Handles WebView21.NavigationCompleted
    Dim firstName = (Await WebView21.
        ExecuteScriptAsync("document.getElementById('m.first_name').textContent;")).
        Trim(ChrW(34))

    Debug.WriteLine(firstName)
End Sub

You could try the querySelector() method as well:

Private Async Sub WebView2_NavigationCompletedAsync(
                    sender As Object,
                    e As CoreWebView2NavigationCompletedEventArgs) _
                    Handles WebView21.NavigationCompleted
    Dim firstName = (Await WebView21.
        ExecuteScriptAsync("document.querySelector('#m\\.first_name').textContent;")).
        Trim(ChrW(34))

    Debug.WriteLine(firstName)
End Sub

Leave a Comment

tech