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

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

Mary-Kate Olsen
Release: 2025-01-04 03:18:08
Original
669 people have browsed it

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

To parse and execute JS in C#, you can use the Windows Script Engines. These engines support both 32-bit and 64-bit environments.

Here's an example of how to use the ScriptEngine class to parse and execute a simple JavaScript expression:

using System;
using System.Runtime.InteropServices;

namespace ParseAndExecuteJS
{
    class Program
    {
        [DllImport("ole32.dll")]
        private static extern int CoInitialize(IntPtr pvReserved);

        private const string JavaScriptEngineCLSID = "{F414C240-6E10-11cf-9B44-00AA004738B1}";

        static void Main(string[] args)
        {
            // Initialize COM.
            CoInitialize(IntPtr.Zero);

            // Create a new JavaScript engine.
            ScriptEngine engine = new ScriptEngine(JavaScriptEngineCLSID);

            // Parse the JavaScript code.
            ParsedScript parsedScript = engine.Parse("1 + 2");

            // Execute the JavaScript code.
            object result = parsedScript.CallMethod("eval");

            // Print the result.
            Console.WriteLine(result);
        }
    }
}
Copy after login

This code will output the result of evaluating the JavaScript expression "1 2", which is 3.

You can also use the ScriptEngine class to parse and execute more complex JavaScript code, such as functions and objects.

The above is the detailed content of How Can I Parse and Execute JavaScript Code within C#?. 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