c# How to get all row value from cefsharp chromium browser?

780 Views Asked by At

I can take a table's first row's td values from cefsharp chromiumwebbrowser with this code but I need all rows value. How to get each rows value? Thanks for answer.

private void GetTable ()
 {
const string script = @"(function(){
    let table = document.querySelector('table'); // <table class='table table-striped'>
    let td = table.getElementsByTagName('td');
    return [ td[0].innerText, td[1].innerText ];
})();";
browser.GetMainFrame().EvaluateScriptAsync(script).ContinueWith(x =>
{
    var response = x.Result;

    if (response.Success && response.Result != null)
    {
        // We cast values as CefSharp wouldn't know what to expect
        List<object> jsResult = (List<object>)response.Result;

        string s1 = (string)jsResult[0]; // td[0].innerText
        string s2 = (string)jsResult[1]; // td[1].innerText

        Console.WriteLine("s1: " + s1);
        Console.WriteLine("s2: " + s2);
        // In my example HTML page, it will output:
        // s1: This is 1st
        // s2: This is 2nd
    }
});

}

I got this code from https://stackoverflow.com/a/55731493/3809268 Thanks this codes owner.

1

There are 1 best solutions below

1
Alexander On

First, you need to change part of script. Try this:

.
.
.
let td = table.getElementsByTagName('td');
let arr = [];
for (var i = 0; i < td.length; i++) {
    arr.push(td[i].innerText);
}
return arr;

Then change C# code:

.
.
.
if (response.Success && response.Result != null)
{
    List<object> jsResult = (List<object>)response.Result;

    foreach (var item in jsResult)
    {
        Console.WriteLine("s: " + item.ToString());
    }
}

In script we have created array with innerText of each td element. Then use foreach to read each element from your list.