CefSharp get result from existing Javascript function
Asked Answered
P

1

6

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: enter image description here

I've also tried

chromeBrowser.GetMainFrame().EvaluateScriptAsync(script)

but with same results.

Any ideas?

Prance answered 9/1, 2019 at 16:48 Comment(0)
T
6

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();") 

Tripody answered 9/1, 2019 at 20:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.