Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing JavaScript code from C# Winforms

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.

like image 530
Sangram Nandkhile Avatar asked Nov 23 '11 10:11

Sangram Nandkhile


1 Answers

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
        }
    }
like image 175
Jeff Lauder Avatar answered Sep 20 '22 14:09

Jeff Lauder