Search code examples
vb.netwebview2

How can I get the sourcecode and put it in my gridview?


On buttonclick I want to load the url from cell(0) to webwiev2-component, and then when the loading ends, I want to add the sourcecode to cell(4). The goal is to be able to preload websites from a list.

So far I have this, but it only adds System.Threading.Tasks.Task`1[System.String to cell(4) and doesnt wait for the site to load. All help is appreciated much.

        Dim preuri As Uri
        Dim src As String
        Dim rowindex As Integer
        rowindex = DataGridView1.CurrentCell.RowIndex
        Try

            'WebView22.Source = New Uri("https://" + DataGridView1.Rows(rowindex).Cells(0).Value.ToString)
            src = WebView21.CoreWebView2.ExecuteScriptAsync("new XMLSerializer().serializeToString(document);").ToString

            src = System.Text.RegularExpressions.Regex.Unescape(src)
            src = src.Remove(0, 1)
            src = src.Remove(src.Length - 1, 1)
            DataGridView1.Rows(rowindex).Cells(4).Value = src
        Catch ex As Exception
        End Try

    End Sub```

Solution

  • This answer can get you started. You'll probably want some code like:

    Dim html As String
    html = Await WebView2.ExecuteScriptAsync("document.documentElement.outerHTML;")
    html = Regex.Unescape(html)
    

    Note the Await bit. ExecuteScriptAsync() is an async function. It returns a Task(Of String) immediately, you need to await it to get the actual string result.