Skip to content

Calling a single .NET method from JavaScript

paulbartrum edited this page Apr 26, 2016 · 3 revisions

You can call any .NET from JavaScript using the SetGlobalFunction API. For example:

var engine = new Jurassic.ScriptEngine();
engine.SetGlobalFunction("test", new Func<int, int, int>((a, b) => a + b));
Console.WriteLine(engine.Evaluate<int>("test(5, 6)"));

This code will output "11" to the console.

Note the following:

  • The delegate parameter types and return type must all be supported.
  • An exception thrown within the provided delegate cannot be caught within JavaScript (unless it is a JavaScriptException).
  • The above example will not work in Silverlight because of security restrictions. To fix it, pass a delegate to a public method.

Next tutorial: Calling a JavaScript function from .NET