Running Javascript in .net core

If you are looking for a solution of running code library cross environment, you probly think javascript, we need share code/logic through environment, and coding one and once only.

There are 2 ways of excution javascript

  • Headless browser - Internet explorer without UI, you can run js in simulation envireonment.
  • Js Engine/Framework - Excute javascript with engine support

The headless browser:

  • WebKit.Net(free)
  • Awesomium It is based on Chrome/WebKit and works like a charm. There is a free license available but also a commercial one and if need be you can buy the source code
  • HTML Agility Pack (free) (An HTML Parser library, NOT a headless browser)
    This helps with extracting information from HTML etc. and might be useful in your case (possibly in combination with HttpWebRequest)
  • PhantomJS - full featured headless web browser. Often used in pair with Selenium which allows you to access the browser from .NET application.
  • Optimus - lightweight headless web browser. It's in beta but it is sufficient for some cases.

But they ALL dead(2021/1/22), so there is only one way posible.

The JS Engine

// create a script engine
using (var engine = new V8ScriptEngine())
{
    // expose a host type
    engine.AddHostType("Console", typeof(Console));
    engine.Execute("Console.WriteLine('{0} is an interesting number.', Math.PI)");
    // expose a host object
    engine.AddHostObject("random", new Random());
    engine.Execute("Console.WriteLine(random.NextDouble())");
    // expose entire assemblies
    engine.AddHostObject("lib", new HostTypeCollection("mscorlib", "System.Core"));
    engine.Execute("Console.WriteLine(lib.System.DateTime.Now)");
    // create a host object from script
    engine.Execute(@"
    birthday = new lib.System.DateTime(2007, 5, 22);
    Console.WriteLine(birthday.ToLongDateString());
    ");
    // use a generic class from script
    engine.Execute(@"
    Dictionary = lib.System.Collections.Generic.Dictionary;
    dict = new Dictionary(lib.System.String, lib.System.Int32);
    dict.Add('foo', 123);
    ");
    // call a host method with an output parameter
    engine.AddHostObject("host", new HostFunctions());
    engine.Execute(@"
    intVar = host.newVar(lib.System.Int32);
    found = dict.TryGetValue('foo', intVar.out);
    Console.WriteLine('{0} {1}', found, intVar);
    ");
    // create and populate a host array
    engine.Execute(@"
    numbers = host.newArr(lib.System.Int32, 20);
    for (var i = 0; i < numbers.Length; i++) { numbers[i] = i; }
    Console.WriteLine(lib.System.String.Join(', ', numbers));
    ");
    // create a script delegate
    engine.Execute(@"
    Filter = lib.System.Func(lib.System.Int32, lib.System.Boolean);
    oddFilter = new Filter(function(value) {
    return (value & 1) ? true : false;
    });
    ");
    // use LINQ from script
    engine.Execute(@"
    oddNumbers = numbers.Where(oddFilter);
    Console.WriteLine(lib.System.String.Join(', ', oddNumbers));
    ");
    // use a dynamic host object
    engine.Execute(@"
    expando = new lib.System.Dynamic.ExpandoObject();
    expando.foo = 123;
    expando.bar = 'qux';
    delete expando.foo;
    ");
    // call a script function
    engine.Execute("function print(x) { Console.WriteLine(x); }");
    engine.Script.print(DateTime.Now.DayOfWeek);
    // examine a script object
    engine.Execute("person = { name: 'Fred', age: 5 }");
    Console.WriteLine(engine.Script.person.name);
    // read a JavaScript typed array
    engine.Execute("values = new Int32Array([1, 2, 3, 4, 5])");
    var values = (ITypedArray)engine.Script.values;
    Console.WriteLine(string.Join(", ", values.ToArray()));
}