javascriptclearscript

Passing variables to Javascript using ClearScript


I want to run Javascript within C# and pass variables between C# and Javascript.

It seems ClearScript is the current stable way to do this.

I have a JavaScript function that looks something like this:

var b = a[0];
var c = a[1];
var d = a[2];
var e = a[3];
rtnstr = "{errmsg: 'calculation never ran'}";

calculation()

function calculation() {
   rtnstr = "{ one:'" + a+b "', " two:'" + c+d + "'}";
}

How can I call that in ClearScript passing in the a array and fetching back the rtnstr string.

I found this URL: https://clearscript.codeplex.com, which shows how to retrieve an array of integers; I need it to retrieve one String.

I also need to know how to pass in variables; the example does not show that.


Solution

  • I am way late and a dollar short, but here is another solution. I was looking for a quick answer before stumbling across it Intellisense. It sounds like you are looking for ClearScript's "Invoke" method:

    Given that you might have a JavaScript function like:

    function calculation(a) {
        var b = a[0];
        var c = a[1];
        var d = a[2];
        var e = a[3];
    
        return `{{ one: ${(b + c)}, two: ${(d + e)} }}`;
    };
    

    That you wish to call from C# with an array of ints:

    var rtnstr = engine.Invoke("calculation", new int[] { 1, 2, 3, 4, 5 });
    

    Possible bug in ClearScript 5.6: It does not seem to like function variables. I originally tried to declare the function as:

    const calculation = (a) => {
        var b = a[0];
        var c = a[1];
        var d = a[2];
        var e = a[3];
    
        return `{{ one: ${(b + c)}, two: ${(d + e)} }}`;
    };
    

    But I received an exception "Method or property not found". Declaring as a plain old function in the global scope works though.