To parse and execute JS in C#, you can use the provided code snippet. It wraps the Windows Script Engines and supports 32-bit and 64-bit environments. In your specific case, you may need to emulate/implement some HTML DOM elements (using the 'named items' feature, with the MyItem class) depending on the .JS code. This is exactly what Internet Explorer does.
Here are some examples of what you can do with it:
1) Direct expressions evaluation:
Console.WriteLine(ScriptEngine.Eval("jscript", "1+2/3"));
will display 1.66666666666667
2) Function call, with optional arguments:
using (ScriptEngine engine = new ScriptEngine("jscript")) { ParsedScript parsed = engine.Parse("function MyFunc(x){return 1+2+x}"); Console.WriteLine(parsed.CallMethod("MyFunc", 3)); }
This will display 6.
3) Function call with named items, and optional arguments:
using (ScriptEngine engine = new ScriptEngine("jscript")) { ParsedScript parsed = engine.Parse("function MyFunc(x){return 1+2+x+My.Num}"); MyItem item = new MyItem(); item.Num = 4; engine.SetNamedItem("My", item); Console.WriteLine(parsed.CallMethod("MyFunc", 3)); } [ComVisible(true)] // Script engines are COM components. public class MyItem { public int Num { get; set; } }
This will display 10.
Edit: I have added the possibility to use a CLSID instead of a script language name, so we can re-use the new and fast IE9 "chakra" javascript engine, like this:
using (ScriptEngine engine = new ScriptEngine("{16d51579-a30b-4c8b-a276-0ff4dc41e755}")) { // continue with chakra now }
The above is the detailed content of How Can I Parse and Execute JavaScript Code within a C# Application?. For more information, please follow other related articles on the PHP Chinese website!