public CCFixture() { runtime = JsRuntime.Create(JsRuntimeAttributes.AllowScriptInterrupt); context = runtime.CreateContext(); context.AddRef(); typeMapper = new TypeMapper(); }
public async Task TestFunction() { using (var runtime = JsRuntime.Create()) { var called = false; var context = runtime.CreateContext(); await context.DeclareFunctionAsync("run", () => called = true); await context.EvalAsync("run()"); Assert.True(called, "the run function was not callded."); } }
public async Task TestFunctionReturn() { const string expected = "foobar"; using (var runtime = JsRuntime.Create()) { var context = runtime.CreateContext(); await context.DeclareFunctionAsync("run", () => expected); var result = await context.EvalAsync <string>("run()"); Assert.Equal(expected, result); } }
public async Task TestJsProxy() { using (var runtime = JsRuntime.Create()) { var context = runtime.CreateContext(); var instance = new TestClass(); await context.SetGlobalAsync("item", instance); await context.EvalAsync("item.call()"); Assert.True(instance.IsCalled); await context.EvalAsync("item.isCalled = false"); Assert.False(instance.IsCalled); } }
/// <summary> /// Constructs an instance of adapter for the ChakraCore JS engine /// </summary> /// <param name="settings">Settings of the ChakraCore JS engine</param> public ChakraCoreJsEngine(ChakraCoreSettings settings) { ChakraCoreSettings chakraCoreSettings = settings ?? new ChakraCoreSettings(); JsRuntimeAttributes attributes = JsRuntimeAttributes.None; if (chakraCoreSettings.DisableBackgroundWork) { attributes |= JsRuntimeAttributes.DisableBackgroundWork; } if (chakraCoreSettings.DisableNativeCodeGeneration) { attributes |= JsRuntimeAttributes.DisableNativeCodeGeneration; } if (chakraCoreSettings.DisableEval) { attributes |= JsRuntimeAttributes.DisableEval; } if (chakraCoreSettings.EnableExperimentalFeatures) { attributes |= JsRuntimeAttributes.EnableExperimentalFeatures; } _externalObjectFinalizeCallback = ExternalObjectFinalizeCallback; _dispatcher.Invoke(() => { try { _jsRuntime = JsRuntime.Create(attributes, null); _jsContext = _jsRuntime.CreateContext(); _jsContext.AddRef(); } catch (Exception e) { throw new JsEngineLoadException( string.Format(CoreStrings.Runtime_JsEngineNotLoaded, EngineName, e.Message), EngineName, EngineVersion, e); } }); }
/// <summary> /// /// </summary> /// <param name="e"></param> protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); try { var js = new FileInfo(@"test.js"); using (var runtime = JsRuntime.Create()) { runtime.AllocatingMemory += this.Runtime_MemoryEvent; runtime.CollectingGarbage += this.Runtime_CollectingGarbage; using (runtime.CreateContext().Use(true)) { try { var obj = JsExternalObject.Create(this); obj.ExternalData = 12; obj.ExternalData = 100; JsContext.StartDebugging(); var func = JsFunction.Create(saf); var console = Opportunity.ChakraBridge.WinRT.Browser.Console.GetOrCreate(); console.Logging += Con_Logging; var c2 = Opportunity.ChakraBridge.WinRT.Browser.Console.GetOrCreate(); JsValue.GlobalObject["func"] = func; JsContext.RunScript("console.log(1,'2',{});func(1,'2',{});new func();", js.Name); } catch (Exception) { var error = JsContext.LastError; } } } } catch (Exception) { } }
public Runtime(IServiceProvider serviceProvider) { runtime = JsRuntime.Create(JsRuntimeAttributes.AllowScriptInterrupt); this.serviceProvider = serviceProvider; }
/// <summary> /// Constructs an instance of adapter for the ChakraCore JS engine /// </summary> /// <param name="settings">Settings of the ChakraCore JS engine</param> public ChakraCoreJsEngine(ChakraCoreSettings settings) { #if NETFULL Initialize(); #endif ChakraCoreSettings chakraCoreSettings = settings ?? new ChakraCoreSettings(); JsRuntimeAttributes attributes = JsRuntimeAttributes.AllowScriptInterrupt; if (chakraCoreSettings.DisableBackgroundWork) { attributes |= JsRuntimeAttributes.DisableBackgroundWork; } if (chakraCoreSettings.DisableEval) { attributes |= JsRuntimeAttributes.DisableEval; } if (chakraCoreSettings.DisableExecutablePageAllocation) { attributes |= JsRuntimeAttributes.DisableExecutablePageAllocation; } if (chakraCoreSettings.DisableFatalOnOOM) { attributes |= JsRuntimeAttributes.DisableFatalOnOOM; } if (chakraCoreSettings.DisableNativeCodeGeneration) { attributes |= JsRuntimeAttributes.DisableNativeCodeGeneration; } if (chakraCoreSettings.EnableExperimentalFeatures) { attributes |= JsRuntimeAttributes.EnableExperimentalFeatures; } #if NETSTANDARD1_3 _dispatcher = new ScriptDispatcher(); #else _dispatcher = new ScriptDispatcher(chakraCoreSettings.MaxStackSize); #endif _promiseContinuationCallback = PromiseContinuationCallback; try { _dispatcher.Invoke(() => { _jsRuntime = JsRuntime.Create(attributes, null); _jsRuntime.MemoryLimit = settings.MemoryLimit; _jsContext = _jsRuntime.CreateContext(); if (_jsContext.IsValid) { _jsContext.AddRef(); } }); } catch (DllNotFoundException e) { throw WrapDllNotFoundException(e); } catch (Exception e) { throw CoreErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } finally { if (!_jsContext.IsValid) { Dispose(); } } }
static void Main(string[] args) { using (JsRuntime runtime = JsRuntime.Create()) { JsContext context = runtime.CreateContext(); context.AddRef(); JsSourceContext sourceContext = JsSourceContext.FromIntPtr(IntPtr.Zero); var moduleManager = new EsModuleManager(() => sourceContext++); var scope = new JsScope(context); try { JsValue moduleNamespace; // It's not working. Always returns a result equal to `undefined`. JsValue resultValue = moduleManager.EvaluateModuleCode( @"import * as geometry from './geometry/geometry.js'; new geometry.Square(15).area;", "Files/main-with-return-value.js", out moduleNamespace ); WriteLine("Return value: {0}", resultValue.ConvertToString().ToString()); // It's works. We can return the result value by using the default export. moduleManager.EvaluateModuleCode( @"import * as geometry from './geometry/geometry.js'; export default new geometry.Square(20).area;", "Files/main-with-default-export.js", out moduleNamespace ); JsPropertyId defaultPropertyId = JsPropertyId.FromString("default"); JsValue defaultPropertyValue = moduleNamespace.GetProperty(defaultPropertyId); WriteLine("Default export: {0}", defaultPropertyValue.ConvertToString().ToString()); // It's works. We can return the result value by using the named export. moduleManager.EvaluateModuleCode( @"import * as geometry from './geometry/geometry.js'; export let squareArea = new geometry.Square(25).area;", "Files/main-with-named-export.js", out moduleNamespace ); JsPropertyId squareAreaPropertyId = JsPropertyId.FromString("squareArea"); JsValue squareAreaPropertyValue = moduleNamespace.GetProperty(squareAreaPropertyId); WriteLine("Named export: {0}", squareAreaPropertyValue.ConvertToString().ToString()); } catch (JsException e) { WriteLine("During working of JavaScript engine an error occurred."); WriteLine(); Write(e.Message); var scriptException = e as JsScriptException; if (scriptException != null) { WriteLine(); JsValue errorValue = scriptException.Metadata.GetProperty("exception"); JsValueType errorValueType = errorValue.ValueType; if (errorValueType == JsValueType.Error || errorValueType == JsValueType.Object) { JsValue messageValue; JsPropertyId stackPropertyId = JsPropertyId.FromString("stack"); if (errorValue.HasProperty(stackPropertyId)) { messageValue = errorValue.GetProperty(stackPropertyId); } else { messageValue = errorValue.GetProperty("message"); } WriteLine(messageValue.ToString()); } else if (errorValueType == JsValueType.String) { WriteLine(errorValue.ToString()); } else { WriteLine(errorValue.ConvertToString().ToString()); } } } finally { scope.Dispose(); moduleManager?.Dispose(); context.Release(); } } }