Reputation: 7782
I want to make sure javascript code is valid syntax:
string test = " var i = 0; ";
Jint.Engine ScrptingEngine = new Jint.Engine();
bool result = ScrptingEngine.Parse(test);
Upvotes: 2
Views: 3120
Reputation: 1765
What about calling the 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).
Then you can catch an Esprima.ParserException
.
Upvotes: 1
Reputation: 365
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.
Upvotes: 1
Reputation: 33833
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.
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:
try
{
ScrptingEngine.Execute("xx = ss == esfx = fuct()");
}
catch(JavaScriptException ex) {}
Upvotes: 1