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. 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# winfrom 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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With