JavaScript code execution from C # Winforms

I am trying to execute JavaScript using Winforms, and I would like to get text from JavaScript code. I need to translate multiple lines using the Google Translator service. came across this nice javascript code that translates this message and displays it in a warning window.

<html> <head> <script type='text/javascript' src='http://www.google.com/jsapi'></script> <script type='text/javascript'> google.load('language','1'); function init () { google.language.translate('How are you?', 'en', 'es', function (translated) { alert(translated.translation); }); } google.setOnLoadCallback(init); </script> </head> <body> </body> </html> 

is there any way that I can pass any line instead of "How are you?" and if I can get the translated text (from a warning window or using any var ) in the context of winfrom C #.

+4
source share
1 answer

Ok, I did a little research. So add a web browser to your form, then I'm sure this will work for you:

  public Form1() { InitializeComponent(); webBrowser1.ObjectForScripting = new MyScript(); } private void Form1_Load(object sender, EventArgs e) { string myTranslatedText = "Hello, how are you?"; webBrowser1.DocumentText = @" <html> <head> <script type='text/javascript' src='http://www.google.com/jsapi'></script> <script type='text/javascript'> google.load('language','1'); function init () { google.language.translate('" + myTranslatedText + @"', 'en', 'es', function (translated) { window.external.CallServerSideCode(translated.translation); }); } google.setOnLoadCallback(init); </script> </head> <body> </body> </html>"; } [ComVisible(true)] public class MyScript { public void CallServerSideCode(string myResponse) { Console.WriteLine(myResponse); //do stuff with response } } 
+2
source

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


All Articles