I'm trying to get the result from an existing Javascript function on a local html page, by using CefSharp in a Windows Form application.
The html page source is:
<!DOCTYPE html>
<html>
<body>
<p id="demo">A Paragraph.</p>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = true;
    return 1 + 1;
}
</script>
</body>
</html>
My C# code is:
private void ChromeBrowser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
    if (!args.IsLoading)
    {
        string result = RunScriptParamAsync("myFunction").ToString();
    }
}
public string RunScriptParamAsync(string scriptName)
{
    string script = "";
    script = scriptName;
    //script = string.Format("(function myFunction() {{ document.getElementById('demo').innerHTML = \"{0}\"; return 1 + 1; }})();", scriptName);
    chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
    {
        var response = x.Result;
        if (response.Success && response.Result != null)
        {
            dynamic result = response.Result;
            return ((int)result).ToString();
        }
        else
        {
            return string.Empty;
        }
    });
    return string.Empty;
}
If I use the commented line
//script = string.Format("(function myFunction() {{ document.getElementById('demo').innerHTML = \"{0}\"; return 1 + 1; }})();", scriptName);
then I'm getting the correct result (2), but the idea is to use a Javascript function already existing on a web page.
A breakpoint inside the function reveals this:

I've also tried
chromeBrowser.GetMainFrame().EvaluateScriptAsync(script)
but with same results.
Any ideas?
You are getting exactly what you are asking for, a reference to the function.You need to append (); to actually execute the function. 
//Will return a IJavascriptCallback, which is effectively a function pointer, which is what you have asked for
await browser.EvaluateScriptAsync("myFunction"); 
//To execute the function you must append (); 
await browser.EvaluateScriptAsync("myFunction();") 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With