I am trying to execute JavaScript using Winforms & I would like to fetch text from JavaScript code. I need to translate few lines using Google Translator service. I came across this nice Javascript code which translates given message & display it in the alert box:
<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 so that I can pass any string instead of 'How are you?' & if I can fetch the translated text (from alert box or using any var
) in the C# WinForms context.
Ok I did a little research. So add a webbrowser to your form, then I bet this will work well 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
}
}