How can I get an HtmlElementCollection from webview2

4.9k Views Asked by At

My old WinForm application used HtmlElementCollection to process a page

        HtmlDocument doc = Browser.Document;
        HtmlElementCollection elems = doc.GetElementsByTagName("table");
        HtmlElement a = elems[0];
        int[] Hucrn = new int[] { 0, 1, 2, 3, 4, 5, 6, };
        HtmlElementCollection satirlar = a.GetElementsByTagName("tr");

ı want to use webview2. But I am not getting htmlelementcollection.

Does anyone know of a way to do this?

1

There are 1 best solutions below

2
amaitland On

As an alternative to using JavaScript to interact with the DOM you can install WebView2.DevTools.Dom from Nuget.org. It's free for anyone to use. Project on GitHub.

Your code would look something like:

await webView.EnsureCoreWebView2Async();
 
 // Create one instance per CoreWebView2
 // Reuse devToolsContext if possible, dispose (via DisposeAsync) before creating new instance
 // Make sure to call DisposeAsync when finished or await using as per this example
// Add using WebView2.DevTools.Dom; to access the CreateDevToolsContextAsync extension method
await using var devToolsContext = await webView2Browser.CoreWebView2.CreateDevToolsContextAsync();

//Get all table elements
var tableElements = await devtoolsContext.QuerySelectorAllAsync<HtmlTableElement>("table");

var table = tableElements[0];

var body = await table.GetBodyAsync();
var rows = await body.GetRowsAsync().ToArrayAsync();

foreach (var row in rows)
{
    var cells = await row.GetCellsAsync().ToArrayAsync();

    foreach (var cell in cells)
    {
        await table.SetInnerHtmlAsync("Updated Div innerText");
    }
}

//Alternatively Get a reference to the HtmlCollection and use async enumerable
//Requires Net Core 3.1 or higher
var tableRowsHtmlCollection = await table.GetRowsAsync();

await foreach (var row in tableRowsHtmlCollection)
{
    var cells = await row.GetCellsAsync();
    await foreach (var cell in cells)
    {
        var newDiv = await devToolsContext.CreateHtmlElementAsync<HtmlDivElement>("div");
        await newDiv.SetInnerTextAsync("New Div Added!");
        await cell.AppendChildAsync(newDiv);
    }
}


//Alternatively use querySelector syntax to directly return all cells within a table
//https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector#examples
//Get all table elements
var tableCells = await devtoolsContext.QuerySelectorAllAsync<HtmlTableCellElement>("table td");

foreach (var cell in tableCells)
{
    await table.SetInnerHtmlAsync("Updated Div innerText");
}

More details and examples in the Readme. I'm working on a guide for those porting from the old IE WebBrowser which is at https://github.com/ChromiumDotNet/WebView2.DevTools.Dom/discussions/3