using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNetBrowser;
using DotNetBrowser.Events;
using System.Threading;

namespace ExecuteJavaScript
{
    class Program
    {
        static void Main(string[] args)
        {
            using (Browser browser = BrowserFactory.Create())
            {
                ManualResetEvent waitEvent = new ManualResetEvent(false);
                browser.FinishLoadingFrameEvent += delegate(object sender, FinishLoadingEventArgs e)
                {
                    // Wait until main document of the web page is loaded completely.
                    if (e.IsMainFrame)
                    {
                        // Execute JavaScript code and get return value from JavaScript.
                        JSValue returnValue = e.Browser.ExecuteJavaScriptAndReturnValue("someFunction");
                        // Make sure that return value is a function.
                        if (returnValue.IsFunction())
                        {
                            String val="Hello World";
                            JSValue result = returnValue.AsFunction().InvokeAndReturnValue(null,val);
                            if (result.IsString())
                            {
                                System.Diagnostics.Debug.WriteLine("result = " + result.AsString().GetString());
                            }
                        }
                        waitEvent.Set();
                    }
                };
                browser.LoadHTML("<html><head><script>function someFunction(data){return data;}</script></head><body></body></html>");
                waitEvent.WaitOne();
            }
        }
    }
}