Search code examples
c#awesomium

How to return JavaScript results back to C# with Awesomium?


I created a new WPF project, and added a Awesomium 1.6.3 WebControl to it.

Then, I added this code to MainWindow.xaml.cs:

    private void webControl1_Loaded(object sender, RoutedEventArgs e)
    {
        webControl1.LoadURL("https://www.google.com/");
    }

    private void webControl1_DomReady(object sender, EventArgs e)
    {
        var wc = new WebClient();
        webControl1.ExecuteJavascript(jQuery);
        webControl1.ExecuteJavascript(@"var __jq = jQuery.noConflict();");
        webControl1.ExecuteJavascript(@"alert(__jq);");
        using(var result = webControl1.ExecuteJavascriptWithResult(@"(function() { return 1; })();"))
        {
            MessageBox.Show(result.ToString());
        }
        //using (var result = webControl1.ExecuteJavascriptWithResult(@"(function() { return __jq('a'); })();"))
        //{
        //    MessageBox.Show(result.ToString());
        //}
    }

And it alerts "1" and then "function (a,b){...}", which is out of order, now that I think about it, but whatever, that's another issue.

As soon as I uncomment the bottom code, it alerts "1" and then hangs. Why? How can I can some information about the links on a page? Or reliably pass some information back to C#? Or get access to the DOM with C#?

Edit: jQuery is just a string containing the jQuery 1.7 code.


Solution

  • Regarding why the following line hangs:

    webControl1.ExecuteJavascriptWithResult(@"(function() { return __jq('a'); })();")
    

    This is because ExecuteJavascriptWithResult can only return basic Javascript types (either a String, Number, Boolean, Array, or a user-created Object). You attempt to return a native DOM Element Object which cannot be mapped to one of these types and so the request fails.