Home > Backend Development > C++ > How Can I Parse and Execute JavaScript Code within a C# Application?

How Can I Parse and Execute JavaScript Code within a C# Application?

Susan Sarandon
Release: 2024-12-27 20:01:12
Original
946 people have browsed it

How Can I Parse and Execute JavaScript Code within a C# Application?

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"));
Copy after login

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));
}
Copy after login

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; }
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template