How to parse and execute JS in C#
The provided C# code includes a class, ScriptEngine, that serves as a wrapper around the Windows Script Engine's COM components. It facilitates both 32-bit and 64-bit environments and allows you to parse and execute JavaScript code.
The code sample offers various ways to interact with the script engine:
Direct expression evaluation:
Console.WriteLine(ScriptEngine.Eval("jscript", "1+2/3"));
This evaluates the given JavaScript expression and prints the result (1.66666666666667).
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 defines a JavaScript function, parses it, and calls the function with the argument 3, printing the result (6).
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 example demonstrates the use of named items, which enables emulating/implementing HTML DOM elements. It sets a named item "My" with a property "Num" set to 4, and calls the function with the argument 3, printing the result (10).
The sample also shows how to use a CLSID instead of a script language name to take advantage of the fast IE9 "chakra" JavaScript engine:
using (ScriptEngine engine = new ScriptEngine("{16d51579-a30b-4c8b-a276-0ff4dc41e755}")) { // continue with chakra now }
The full source code for the ScriptEngine class and sample uses are provided for reference. It includes additional features like:
The above is the detailed content of How to Parse and Execute JavaScript Code within C#?. For more information, please follow other related articles on the PHP Chinese website!