C#调用JavaScript

        private void btn_RunJavaScript_Click(object sender, EventArgs e)
        {
            //string path = AppDomain.CurrentDomain.BaseDirectory + "test.js";
            //string str2 = File.ReadAllText(path);

            //string fun = string.Format(@"sayHello('{0}')", this.textBox1.Text.Trim());
            // object[] para=new object[1];
            // para[0] = str2;
            // string result = JavaScriptHelper.GetJsMethd(fun, para);
            
            string str2 = rtb_JavaScript.Text;
            string fun = string.Format(@"sayHello('{0}')" ,this.textBox1.Text.Trim());
            string result = JavaScriptHelper.ExecuteScript(fun, str2);

            MessageBox.Show(result);

        }

        /// 
        /// 执行JS
        /// 
        /// 参数体
        /// JavaScript代码的字符串
        /// 
        public static 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;
        }

添加COM引用

C#调用JavaScript_第1张图片

你可能感兴趣的:(c#开发)