Execute JavaScript from within a C# assembly

后端 未结 6 2149
既然无缘
既然无缘 2021-02-05 07:08

I\'d like to execute JavaScript code from within a C# assembly and have the results of the JavaScript code returned to the calling C# code.

It\'s easier to define things

6条回答
  •  长发绾君心
    2021-02-05 07:54

    The code should be pretty self explanitory, so I'll just post that.

    
    

    using Microsoft.JScript;
    
    public class MyClass {
    
        public static Microsoft.JScript.Vsa.VsaEngine Engine = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
    
        public static object EvaluateScript(string script)
        {
            object Result = null;
            try
            {
                Result = Microsoft.JScript.Eval.JScriptEvaluate(JScript, Engine);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
    
            return Result;
        }
    
        public void MyMethod() {
            string myscript = ...;
            object myresult = EvaluateScript(myscript);
        }
    }
    

提交回复
热议问题