Home >Backend Development >C++ >How to Parse and Execute JavaScript Code within C#?

How to Parse and Execute JavaScript Code within C#?

Linda Hamilton
Linda HamiltonOriginal
2024-12-31 05:33:09636browse

How to Parse and Execute JavaScript Code within C#?

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:

  • Property retrieval and setting
  • Script exception handling
  • Adding named root-level items to the script engine's name space

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn