在Windows 8 / .Net 4.5中嵌入Chakra Javascript引擎

时间:2011-10-16 03:27:58

标签: javascript .net windows-8 chakra

鉴于Windows 8中Javascript的兴起,Windows 8 / .Net 4.5 / VS 2012是否提供了一种机制来将Chakra javascript引擎嵌入到应用程序中以启用脚本?如果是这样的话,是否有针对此的文档?

3 个答案:

答案 0 :(得分:1)

没有机制可以解决这个问题。目前,它仅适用于IE和Metro风格的应用程序。甚至没有Windows Scripting Host风格的曝光。

您在编写脚本时想要的Chakra是什么?

答案 1 :(得分:0)

IE ActiveX是否使用与IE独立版相同的JavaScript引擎?

您可以简单地嵌入Internet Explorer ActiveX框架并将其隐藏起来。

答案 2 :(得分:0)

是的,存在。

请参阅:https://github.com/Microsoft/ChakraCore/wiki/Embedding-ChakraCore

 using System;
 using System.Runtime.InteropServices;
 using ChakraHost.Hosting;

public class HelloWorld
{
    static void Main() {
    JavaScriptRuntime runtime;
    JavaScriptContext context;
    JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
    JavaScriptValue result;

    // Your script, try replace the basic hello world with something else
    string script = "(()=>{return \'Hello world!\';})()";

    // Create a runtime. 
    Native.JsCreateRuntime(JavaScriptRuntimeAttributes.None, null, out runtime);

    // Create an execution context. 
    Native.JsCreateContext(runtime, out context);

    // Now set the execution context as being the current one on this thread.
    Native.JsSetCurrentContext(context);

    // Run the script.
    Native.JsRunScript(script, currentSourceContext++, "", out result);

    // Convert your script result to String in JavaScript; redundant if your script returns a String
    JavaScriptValue resultJSString;
    Native.JsConvertValueToString(result, out resultJSString);

    // Project script result in JS back to C#.
    IntPtr resultPtr;
    UIntPtr stringLength;
    Native.JsStringToPointer(resultJSString, out resultPtr, out stringLength);

    string resultString = Marshal.PtrToStringUni(resultPtr);
    Console.WriteLine(resultString);
    Console.ReadLine();

    // Dispose runtime
    Native.JsSetCurrentContext(JavaScriptContext.Invalid);
    Native.JsDisposeRuntime(runtime);
}

}