C#中调用javascript

结合网上的代码整理了一下c#中调用js的方法,仅用于留存。

ps.测试用的js文件需要放到bin\Debug下

代码如下:

using System;
using System.IO;

namespace CallJSTest
{
    class Program
    {
        static void Main(string[] args)
        {
            CallJs();
        }

        private static void CallJs()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "test.js";
            string str2 = File.ReadAllText(path);

            string fun = string.Format(@"sayHello('{0}')", "Alex Jiang");
            string result = ExecuteScript(fun, str2);

            Console.Write(result);
            Console.ReadKey();
        }

        /// <summary>
        /// 执行JS
        /// </summary>
        /// <param name="sExpression">参数体</param>
        /// <param name="sCode">JavaScript代码的字符串</param>
        /// <returns></returns>
        private static string ExecuteScript(string sExpression, string sCode)
        {
            var scriptControl = new MSScriptControl.ScriptControl();
            scriptControl.UseSafeSubset = true;
            scriptControl.Language = "JScript";
            scriptControl.AddCode(sCode);
            try
            {
                string str = scriptControl.Eval(sExpression).ToString();
                return str;
            }
            catch (Exception ex)
            {
                string str = ex.Message;
            }
            return null;
        }
    }
}

  

posted @ 2016-09-21 14:01  Alex Jiang  阅读(3152)  评论(1编辑  收藏  举报