Adnan Temur
Adnan Temur

Reputation: 79

How can I get the returned value of javascript using chromium web browser in c#

How can I get the returned value of javascript using chromium web browser. I know how to put a value to a DOM element. But I do not know how to get the DOM element's value using cef sharp. My sample code is like this.

//chromeBrowser = ChromiumWebBrowser object
String script = 
string.Format("document.getElementsByName('DOMElementName') 
[0].value;");
chromeBrowser.EvaluateScriptAsync(script).ContinueWith(x =>
        {
           // I want to use the returned value of the script above
        });

How can I achieve this.

Upvotes: 0

Views: 1560

Answers (1)

Patrick Hollweck
Patrick Hollweck

Reputation: 6665

You may be interested in the official CefSharp FAQ they have on their GitHub.


You need to wait for the FrameLoadEnd event to fire. Only after that can you evaluate a script. Then call EvaluateScriptAsync with the script string you want to execute on the frame, then you get back a Task which will contain the result of the operation.

browser.FrameLoadEnd += (sender, args) =>
{
  var task = args.frame.EvaluateScriptAsync(script, null);

  task.ContinueWith(t =>
  {
    if (!t.IsFaulted)
    {
      var response = t.Result;
      var result = = response.Success ? (response.Result ?? "null") : response.Message;
      // TODO: do something with the result
    }
  }, TaskScheduler.FromCurrentSynchronizationContext());
};

Upvotes: 2

Related Questions