Home >Backend Development >C++ >How to Parse and Execute JavaScript Code within a C# Application?
How to Parse and Execute JavaScript in C#
In this code example, we wrap the Windows Script Engines to support 32-bit and 64-bit environments.
For your specific case, it means depending on the .JS code, you may have to emulate/implement some HTML DOM elements such as 'document', 'window', etc. (using the 'named items' feature, with the MyItem class. That's exactly what Internet Explorer does).
Here are some sample 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)); }
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; } }
Will display 10.
Edit: We 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 }
Here is the full source:
(see provided code)
Usage:
Notes:
The above is the detailed content of How to Parse and Execute JavaScript Code within a C# Application?. For more information, please follow other related articles on the PHP Chinese website!