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

I created a new WPF project and added 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 he warns β€œ1”, and then β€œfunction (a, b) {...}”, which has failed, now that I think about it, but something else, this problem.

As soon as I uncomment the bottom code, it alerts β€œ1” and then freezes. What for? How can I get some information about the links on the page? Or reliably pass some information back to C #? Or access the DOM from C #?

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

+4
source share
2 answers

Regarding the reasons why the following line hangs:

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

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

+5
source

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

For instance:

 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 useful to include Newtonsoft.Json for serialization material.)

+1
source

Source: https://habr.com/ru/post/1380706/


All Articles