Quick Start

Download Jint

Download the latest release files. It contains a single assembly named Jint.dll. Copy it inside a folder of your own.

Create a sample Console application

Open Visual Studio and create a new Console application

Reference the assembly from your project

Add a reference to the assembly by right clicking on the project in Visual Studio, then Add Reference, open in the tab Browse and select the Jint.dll file you previously copied.

Add usings

In the using section of you program, add this statement:

using Jint;

Execute your first script

JintEngine is the only class you need to manipulate. It will host the JavaScript execution engine and run statements. For instance, the script below returns a simple return statement.

object result = new JintEngine().Run("return 21 * 2");
Console.WriteLine(result); // Displays 42

Reuse the script engine

You can reuse scripts by reusing the JintEngine instance.

JintEngine engine = new JintEngine();

// Defines a new function in the environment
engine.Run(@"
  function square(x) { 
    return x * x;
  }";

// Execute the function multiple times
Console.Write(engine.Run("square(1);");
Console.Write(engine.Run("square(2);");
Console.Write(engine.Run("square(3);");

// Displays 149

Use .NET classes from you scripts

It can be very useful to have access to the base class library of the .NET runtime. To do it, just use the fullname of the type you want to use.
The following example uses a StringBuilder and returns the ToString() evaluation of it.

JintEngine engine = new JintEngine();
var result = engine.Run(@"
  var sb = new System.Text.StringBuilder();
  sb.Append('hi, mom');
  sb.Append(3);	
  sb.Append(true);
  return sb.ToString();
";
Console.WriteLine(result);

// Displays 'hi, mom3true'

Use external parameters

You can define variables in the environment from the host application.

JintEngine engine = new JintEngine();
engine.SetParameter("i", 30);
engine.SetParameter("j", 12);
 
var result = engine.Run(@"
  return i + j;
";

Console.WriteLine(result); // 42

Use external functions

You can define functions from the host application. This is done by providing a Delegate (a function reference) to the environment.

JintEngine engine = new JintEngine();
engine.SetFunction("square", new Func<double, double>(a => { return a * a; }))
var result = engine.Run("return square(3);"));
Console.WriteLine(result); // 9

Last edited Oct 24, 2009 at 10:29 AM by sebastienros, version 2

Comments

tormaroe Jun 23, 2011 at 10:05 AM 
The example code on this page contains a lot of small errors - like missing closing brackets all over the place.

BrainSlugs83 Apr 15, 2011 at 7:16 AM 
Ahh... looks like I just needed to make my class public so JInt could see it! Oops.

BrainSlugs83 Apr 15, 2011 at 7:10 AM 
I'm having a hard time exposing custom .NET objects to JInt scripts using engine.SetParameter... maybe there is another way. Time to hit the manual.