27
05/2017
c#运行JS代码
Jint,
Gitbub网址:https://github.com/sebastienros/jint
编译好的dll文件:https://pan.baidu.com/s/1qYhSM64
使用方法示例:
class Program { static Jint.Engine _engine; public static void Print(object s) { if (s == null) s = "null"; Console.WriteLine(s.ToString()); } private static Jint.Engine CreateEngine() { return new Engine().SetValue("print", new Action<object>(Print)); } static void Main(string[] args) { var source = @" var s = 'Hello World From JavaScript '; for(var i=0; i<4; i++) { print(s + i); } s; // Evaluate and return the expression "; var s = CreateEngine().Execute(source).GetCompletionValue(); Console.WriteLine(s.AsString()); Console.ReadLine(); } }
private static string ExecuteScript(string jsCode) { var engine = new Engine(); engine.Execute(jsCode); return engine.GetCompletionValue().AsString(); }
更多教程,访问:http://frederictorres.blogspot.jp/2014/04/jint-tutorials.html
注意,Jint默认不支持escape和unescape函数,如果代码中有用到这两个函数,需要自己自定义一下。
var escape = function (s) { s = s.toString(s); var n = s.length; var result = ""; for(var k = 0; k < n; k++) { var c = s[k]; var S = ""; var code = c.charCodeAt(0); if(("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./").indexOf(c) > -1) { S = c; } else if(code < 256) { S = '%' + code.toString(16); } else { S = code.toString(16); S = "%u" + ("0000").substring(0, 4 - S.length) + S; } result = result + S; } return result; }; var unescape = function (s) { s = s.toString(s); var n = s.length; var result = ""; for(var k = 0; k < n; k++) { var c = s[k]; if(c == '%') { if(k <= (n - 6)) { if(s[k + 1] == 'u') { if(("0123456789abcdef").indexOf(s[k + 2]) > -1 && ("0123456789abcdef").indexOf(s[k + 3]) > -1 && ("0123456789abcdef").indexOf(s[k + 4]) > -1 && ("0123456789abcdef").indexOf(s[k + 5]) > -1) { c = String.fromCharCode(parseInt(s.substring(k + 2, k + 7), 16)); k = k + 5; } else { if(k <= (n - 3) && ("0123456789abcdef").indexOf(s[k + 1]) > -1 && ("0123456789abcdef").indexOf(s[k + 2]) > -1) { c = String.fromCharCode(parseInt(("00" + s.substring(k + 1, k + 3)), 16)); k = k + 2; } } } else { if(k <= (n - 3) && ("0123456789abcdef").indexOf(s[k + 1]) > -1 && ("0123456789abcdef").indexOf(s[k + 2]) > -1) { c = String.fromCharCode(parseInt(("00" + s.substring(k + 1, k + 3)), 16)); k = k + 2; } } } else if(("0123456789abcdef").indexOf(s[k + 1]) > -1 && ("0123456789abcdef").indexOf(s[k + 2]) > -1) { c = String.fromCharCode(parseInt(("00" + s.substring(k + 1, k + 3)), 16)); k = k + 2; } } result = result + c; } return result; };
0 条评论