Bill Software Engineer
Bill Software Engineer

Reputation: 7782

How do I parse javascript code in Jint interpreter?

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

Answers (3)

specimen
specimen

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

NeutronCode
NeutronCode

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

David L
David L

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

Related Questions