[英]How do I parse javascript code in Jint interpreter?
I want to make sure javascript code is valid syntax:我想确保 javascript 代码是有效的语法:
string test = " var i = 0; ";
Jint.Engine ScrptingEngine = new Jint.Engine();
bool result = ScrptingEngine.Parse(test);
You can use the Execute()
method to "parse" your JavaScript and the GetValue()
method to retrieve the value and then assert that it works as intended. 您可以使用
Execute()
方法来“解析” JavaScript,而可以使用GetValue()
方法来检索该值,然后断言它可以按预期工作。
string test = " var i = 0; ";
Jint.Engine ScrptingEngine = new Jint.Engine();
var result = ScrptingEngine.Execute(test).GetValue("i");
Assert.AreEqual(0, result);
In addition, the Execute
method will also throw a JavaScriptException
if the JavaScript is invalid: 此外,如果JavaScript无效,
Execute
方法还将抛出JavaScriptException
:
try
{
ScrptingEngine.Execute("xx = ss == esfx = fuct()");
}
catch(JavaScriptException ex) {}
If you add the script to a object it should not run any of the code. 如果将脚本添加到对象,则不应运行任何代码。
var myscript = @"
var badFunction = function(){/* please don't run this*/ }
badFunction ();"
new Engine().Execute("var noRun = {" + myscript + "}");
There is no guarantees though that the script itself doesn't break the object incapsulation. 尽管脚本本身不会破坏对象封装,但不能保证。
What about calling the JavaScriptParser?调用 JavaScriptParser 怎么样?
Esprima.JavaScriptParser parser = new Esprima.JavaScriptParser(script);
parser.ParseScript();
When you add Jint to your project, you also get the Esprima namespace, and this is what Jint uses internally anyway (if I read the source correctly).当您将 Jint 添加到您的项目时,您还会获得 Esprima 命名空间,无论如何这就是 Jint 在内部使用的名称(如果我正确阅读了源代码)。
Then you can catch an Esprima.ParserException
.然后你可以捕获一个
Esprima.ParserException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.