C#处理JavaScript引擎

概述

  通常JavaScript在Web浏览器执行展现特定效果,C#也可以后台执行JavaScript里面方法;C#通常调用第三方DLL方式:MsieJavaScriptEngine或者JavaScriptEngineSwitcher。具体使用列举如下;

MsieJavaScriptEngine使用

  Nuget里面,添加MsieJavaScriptEngine的类库;由于MsieJavaScriptEngine不支持.NET Core下Linux的部署运行,代码使用方式如下:

public static string Ck3(string cert, string ts, string nullPara, string page, string token)
        {
            var basePath = AppDomain.CurrentDomain.BaseDirectory;
            using (var jsEngine = new MsieJsEngine())
            {
                jsEngine.ExecuteFile(string.Format(@"{0}/Scripts/myscript.js", basePath));
                string[] arr = new string[] { cert, ts, nullPara, page, token };
                jsEngine.Execute("var $CFMethod=$.ck;");
                var publickey = jsEngine.CallFunction("$CFMethod", arr);
                return publickey.ToString();
            }
        }

 

JavaScriptEngineSwitcher的使用

       Nuget里面,添加JavaScriptEngineSwitcher的类库;由于JavaScriptEngineSwitcher支持.NET Core下Linux和Win的部署运行,另外还需要安装的类库

JavaScriptEngineSwitcher.ChakraCore.Native.linux-x64  ///针对Linux-x64环境下组件;

JavaScriptEngineSwitcher.ChakraCore.Native.win-x64   //针对Wind-x64环境下组件;

JavaScriptEngineSwitcher.ChakraCore.Native.win-x32   //针对Wind-x32环境下组件;

代码使用方式如下:

 public static string Ck(string cert, string ts, string nullPara, string page, string token)
        {
            var basePath = AppDomain.CurrentDomain.BaseDirectory;
            IJsEngineSwitcher engineSwitcher = JsEngineSwitcher.Current;
            engineSwitcher.EngineFactories.Add(new ChakraCoreJsEngineFactory());
            engineSwitcher.DefaultEngineName = ChakraCoreJsEngine.EngineName;
            using (IJsEngine engine = JsEngineSwitcher.Current.CreateDefaultEngine())
            {
                engine.ExecuteFile(string.Format(@"{0}/Scripts/myscipt.js", basePath));
                string[] arr = new string[] { cert, ts, nullPara, page, token };
                engine.Execute("var $CFMethod=$.ck;");
                var publickey = engine.CallFunction("$CFMethod", arr);
                return publickey.ToString();
            }                        
        }

 

你可能感兴趣的:(C#处理JavaScript引擎)