Executing JavaScript code from C# Winforms

☆樱花仙子☆ 提交于 2019-12-07 08:10:20

问题


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.


回答1:


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
        }
    }


来源:https://stackoverflow.com/questions/8240746/executing-javascript-code-from-c-sharp-winforms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!