Calling a JS Function from a script that has been exectued

Sep 15, 2016 at 2:20 PM
So the issue is this, I need to load a script and execute the script, and keep it's state, for a subsequent call to a function within the script based upon a UI event.

For example:

A script:

var hello = "hello";

function spanishHello() { hello = "hola"; }
function englishHello() { hello = "hello"; }
function newyorkHello() { hello = "screw you"; }

spanishHello();

Console.WriteLine(hello);


That script is executed in the engine:

scriptEngine.Execute(script);

that works fine.

At a later point I need to call spanishHello(). It appears that the answer is scriptEngine.Invoke("spanishHello", null); but that throws a not found exception.

I suspect I'm making this harder than it needs to be. Your thoughts and suggestions?
Coordinator
Sep 15, 2016 at 2:43 PM
Hi dru_satori,

scriptEngine.Invoke("spanishHello") should work; another possibility is scriptEngine.Script.spanishHello().

Are you sure you're using the same engine instance that executed the script? Is it possible that you're deleting the functions somehow? What exactly does the exception say? Could you provide a minimal code sample that reproduces the issue?

Thanks!
Sep 15, 2016 at 2:46 PM
I'll have to see if I can pull it apart and give you a test case. The error I'm getting is 'Invalid object or property access' thrown as Microsoft.ClearScript.ScriptingEngineException.
Coordinator
Sep 15, 2016 at 3:20 PM
Hi again,

That message would be expected if you used different JScriptEngine instances to run the script and invoke the function. Are you sure that's not the case?

Cheers!
Sep 15, 2016 at 6:26 PM
It is the same instance, but I think I've found the issue. The prior execute is failing, because for some reason it's throwing a missing ; error during the execute (compiling pretty common JS code, jquery.js... guess I need to sort out what's going on there.