这个问题可以参考http://stackoverflow.com/questions/172753/embedding-javascript-engine-into-net
最近在写一个webqq模拟程序,其中加密算法需要用一个js文件里的方法。于是就需要考虑如何在C#中执行js代码。
方案1:使用Webbrowser
特点:兼容性好,但调用的方式难看了一些
可以参考这个问题可以参考http://www.cnblogs.com/lianmin/p/4231411.html
方案2:使用ScriptControl
特点:无需添加引用。只能工作在32位。
可以参考http://www.sufeinet.com/thread-10007-1-1.html
Type obj = Type.GetTypeFromProgID("ScriptControl");
if (obj == null) return; //单身? 找不到对象啊,
object ScriptControl = Activator.CreateInstance(obj);
obj.InvokeMember("Language", BindingFlags.SetProperty, null, ScriptControl, new object[] { "JScript" });
string js = "function time(){return new Date().getTime()}";
obj.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { js });
string str = obj.InvokeMember("Eval", BindingFlags.InvokeMethod, null, ScriptControl, new object[] { "time()" }).ToString();
textBox1.Text = str;
特点,种类繁多,效率各不相同。
我试了下面两种:
(1)V8.Net,项目地址https://v8dotnet.codeplex.com
包含x86,x64版,引用V8.Net.dll 和V8.Net.SharedTypes.dll添加到项目后,然后复制x86和x64文件夹到exe所在目录
特点,效率据说很高,不过就是太大了,要引用的文件一共100多m,可以自行改造
(2)jint,托管在github上
特点:轻量级,一共200多k,平台无关
string code = string.Format("getPassword('{0}','{1}','{2}')", args);
var engine = new Engine();
engine.Execute(source); //source是js文件的文本字符串
string s = engine.Execute(code).GetCompletionValue().AsString();
我的小项目里最终选用的就是jint,因为项目中用js的地方不多,所以就本着方便的原则了。