C# 调用、执行 js 方法

首先需要引用程序集 Microsoft Script Control 1.0

然后新建一个js文件,并写入相应的js方法

//执行JS文件
        private void btnjs_Click(object sender, EventArgs e)
        {
            //读取js文件路径
            string path = AppDomain.CurrentDomain.BaseDirectory + "JavaScript1.js";
            //加载js文件的所有内容 保存到变量str2中
            string str2 = System.IO.File.ReadAllText(path);
            //调用js方法,如果该js方法有参数,就传呗
            string fun = string.Format(@"sayHello('{0}','{1}','{2}')", 23,34,"+");
            //执行,并得到返回结果
            string result = ExecuteScript(fun, str2);

            MessageBox.Show(result);
        }
        /// <summary>
        /// 执行JS
        /// </summary>
        /// <param name="sExpression">参数体</param>
        /// <param name="sCode">JavaScript代码的字符串</param>
        /// <returns></returns>
        private string ExecuteScript(string sExpression, string sCode)
        {
            MSScriptControl.ScriptControl 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 @ 2015-01-24 11:11  JasonGu0  阅读(10927)  评论(0编辑  收藏  举报