How to return JavaScript results back to C# with A

2019-05-03 23:35发布

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.

标签: c# awesomium
2条回答
Viruses.
2楼-- · 2019-05-03 23:59

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.

查看更多
Animai°情兽
3楼-- · 2019-05-04 00:19

An easy way to return complex objects would be to convert into a string using JSON.stringify(), then parse back out in your C# managed code.

For example:

JSValue rawToken = browser.ExecuteJavascriptWithResult(@"JSON.stringify(someTokenObjectHere);");
if (rawToken.IsString)
{
    // For generic objects:
    JObject payload = JObject.Parse(rawToken.ToString());
    // For typed objects:
    MyCustomTokenObject payload = JsonConvert.DeserializeObject<MyCustomTokenObject>(rawToken.ToString());
}

(It may be advantageous to include Newtonsoft.Json for the serialization stuff.)

查看更多
登录 后发表回答