With the release of IronJS 0.2, the code below is the result of a 30-minute play I had this morning, which shows how easy it is to embed a fully .NET JavaScript runtime in your application by simply referencing IronJS.dll.
It’s changed quite a from prior versions and I think you’ll see it has become much easier to host since Dan Newcombe’s experiments last year.
//reference IronJS.dll using System; using System.IO; class IronJsDoodles { static void Simple() { var context = new IronJS.Hosting.CSharp.Context(); object result = context.Execute("1 + 2;"); Console.WriteLine("{0} ({1})", result, result.GetType()); // "3 (System.Double)" } static void InteractingWithGlobal() { var context = new IronJS.Hosting.CSharp.Context(); context.SetGlobal("a", 1d); context.SetGlobal("b", 2d); context.Execute("foo = a + b;"); double foo = context.GetGlobalAs<double>("foo"); Console.WriteLine(foo); // "3" } static void AddingHostFunctions() { var context = new IronJS.Hosting.CSharp.Context(); // Effectively the same as context.CreatePrintFunction() 🙂 var print = IronJS.Native.Utils.createHostFunction<Action<string>>(context.Environment, delegate(string str) { Console.WriteLine(str); }); context.SetGlobal("print", print); context.Execute("print('Hello IronJS!')"); } }
Hope it helps you get started.
Heya, thanks for the kind words about IronJS. We have been putting effort into making IronJS easier to host and easier to get.
You may be happy to hear that we are now supporting the C# `dynamic` keyword as a way to interact with JavaScript objects in our master branch. You can expect to see that up on NuGet within the next few days.
Thanks John – really looking forward to trying it out!
Is this in 0.2.0.1 or will it be in the next version? ETA? Code sample using ‘dynamic’? Thanks!
The `dynamic` features are available by treating the Context’s `Global` object as `dynamic` in release 0.2.0.1