从c# Winforms执行JavaScript代码

本文关键字:JavaScript 代码 执行 Winforms | 更新日期: 2023-09-27 18:15:33

我正在尝试使用Winforms执行JavaScript &我想从JavaScript代码中获取文本。我需要翻译几行使用谷歌翻译服务。我遇到了这个很好的Javascript代码,它可以翻译给定的消息&在警告框中显示:

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

有没有办法让我可以传递任何字符串而不是'How are you?",如果我可以获取翻译文本(从警告框或使用任何var)在c# WinForms上下文中

从c# Winforms执行JavaScript代码

我做了一点调查。所以添加一个浏览器到你的表单,然后我打赌这将为您工作得很好:

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