问题
2020年了网上C#调用Js的方法还是
1、引用webbrowser控件,简直是刁难我控制台!
2、引用Interop.MSScriptControl.dll
private static object ExecuteScript(string argument, string jsCode)
{
MSScriptControl.ScriptControl scriptControl = new MSScriptControl.ScriptControl();
scriptControl.UseSafeSubset = true;
scriptControl.Language = "JScript";
scriptControl.AddCode(jsCode);
try
{
return scriptControl.Eval(argument);
}
catch (Exception exception)
{
}
return null;
}
但是此程序集已经长久不更新了,JavaScript ES5不支持,从网上下载的版本:
报错:
System.Runtime.InteropServices.COMException:“Retrieving the COM class factory for component with CLSID {0E59F1D5-1FBE-11D0-8FF2-00A0D10038BC} failed due to the following error: 80040154 没有注册类 (0x80040154 (REGDB_E_CLASSNOTREG)).”
解决方案
nuget引入V8.Net:
将DLL文件拷贝到输出目录:
c#调用即可:
c#/Javascript可以互相传递/调用对象
private readonly static string JsPath = Directory.GetCurrentDirectory() + "/your.js";
public static object ExecuteJavaScript(string cityid, string page)
{
string code = File.ReadAllText(JsPath);
V8Engine engine = new V8Engine();
engine.RunMarshallingTests();
//定义可以在JS中使用的全局变量,string/value
engine.GlobalObject.SetProperty("cityid_CSObject", cityid);
engine.GlobalObject.SetProperty("page_CSObject", page);
//js中return object
string result = engine.ConsoleExecute(code).AsString;
return result;
}