private void CreateRegisterComponentFunction() { var id = "registerComponent".ToJavaScriptPropertyId(); var function = JavaScriptValue.CreateFunction(RegisterComponent, IntPtr.Zero); ChakraHost.GlobalObject.SetProperty(id, function, true); }
private static void DefineHostCallback(JavaScriptValue anObject, string callbackName, JavaScriptNativeFunction callback, IntPtr callbackData) { JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString(callbackName); JavaScriptValue function = JavaScriptValue.CreateFunction(callback, callbackData); anObject.SetProperty(propertyId, function, true); }
public void AddType(JavaScriptValue parent, string name, Type type) { // Create the function that will call the class constructor var constructor = JavaScriptValue.CreateFunction(new JavaScriptNativeFunction((callee, isConstructCall, arguments, argumentCount, callbackData) => { return(ToJavaScriptValue(Activator.CreateInstance(type))); })); // Add static functions (e.g Console.WriteLine) if (type.IsClass && type != typeof(string)) { // Get the properties and methods var methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static) .Where(m => !m.IsSpecialName && m.IsPrivate == false).ToList(); // Loop through all methods foreach (var method in methods) { SetMethod(constructor, method, null); } } // Set the property var childPropertyId = JavaScriptPropertyId.FromString(name); parent.SetProperty(childPropertyId, constructor, true); }
public void RegisterObject(string name, object obj) { var type = obj.GetType(); using (new JavaScriptContext.Scope(context)) { var jsObj = JavaScriptValue.CreateObject(); foreach (var m in type.GetMethods()) { var attrib = m.GetCustomAttribute <JsExport>(); if (attrib == null) { continue; } var funcName = attrib.JavaScriptMethodName ?? m.Name; var funcNameProp = JavaScriptPropertyId.FromString(funcName); var funcDelegate = (JavaScriptNativeFunction)Delegate.CreateDelegate(typeof(JavaScriptNativeFunction), obj, m); registeredFunctions.Add(funcDelegate); var funcObj = JavaScriptValue.CreateFunction(funcDelegate); jsObj.SetProperty(funcNameProp, funcObj, true); } var nameProp = JavaScriptPropertyId.FromString(name); JavaScriptValue.GlobalObject.SetProperty(nameProp, jsObj, true); } }
// Example: Register JavaScript object in current frame. private void RegisterJavaScriptExampleObject() { var jsDemo = JavaScriptValue.CreateObject(); jsDemo.SetValue("executeJavaScriptWithoutRetval", JavaScriptValue.CreateFunction(args => { InvokeIfRequired(() => { ExecuteJavaScript("alert(1+1)"); }); return(null); })); jsDemo.SetValue("executeJavaScriptWithRetval", JavaScriptValue.CreateFunction(args => { InvokeIfRequired(async() => { var result = await EvaluateJavaScriptAsync("(function(){ return {a:1,b:'hello',c:(s)=>alert(s)}; })()"); if (result.Success) { var retval = result.ResultValue; MessageBox.Show($"a={retval.GetInt("a")} b={retval.GetString("b")}", "Value from JS"); await retval.GetValue("c").ExecuteFunctionAsync(GetMainFrame(), new JavaScriptValue[] { JavaScriptValue.CreateString("Hello from C#") }); } }); return(null); })); RegisterExternalObjectValue("jsExamples", jsDemo); }
public void Init() { JavaScriptNativeFunction printFunc = PrintFunc; registeredFunctions.Add(printFunc); JavaScriptNativeFunction httpFunc = JsXmlHttpRequest.JsConstructor; registeredFunctions.Add(httpFunc); using (new JavaScriptContext.Scope(context)) { var printFuncName = JavaScriptPropertyId.FromString("print"); var printFuncObj = JavaScriptValue.CreateFunction(printFunc); JavaScriptValue.GlobalObject.SetProperty(printFuncName, printFuncObj, true); var logObj = JavaScriptValue.CreateObject(); var logFuncName = JavaScriptPropertyId.FromString("log"); logObj.SetProperty(logFuncName, printFuncObj, true); var consoleName = JavaScriptPropertyId.FromString("console"); JavaScriptValue.GlobalObject.SetProperty(consoleName, logObj, true); var xmlHttpRequestName = JavaScriptPropertyId.FromString("XMLHttpRequest"); var httpFuncObj = JavaScriptValue.CreateFunction(httpFunc); JavaScriptValue.GlobalObject.SetProperty(xmlHttpRequestName, httpFuncObj, true); } }
private void CreateRunShibaAppFunction() { var id = "runShibaApp".ToJavaScriptPropertyId(); var function = JavaScriptValue.CreateFunction(RunShibaApp, IntPtr.Zero); ChakraHost.GlobalObject.SetProperty(id, function, true); }
private void InstallNativeRequire() { _nativeRequire = NativeRequire; EnsureGlobalObject().SetProperty( JavaScriptPropertyId.FromString("nativeRequire"), JavaScriptValue.CreateFunction(_nativeRequire), true); }
static void _define(JavaScriptValue globalObject, string callbackName, JavaScriptNativeFunction callback) { JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString(callbackName); JavaScriptValue function = JavaScriptValue.CreateFunction(callback, IntPtr.Zero); globalObject.SetProperty(propertyId, function, true); m_apis.Add(callbackName); }
public void RegisterGlobalFunction(string name, JavaScriptNativeFunction func) { registeredFunctions.Add(func); using (new JavaScriptContext.Scope(context)) { var funcName = JavaScriptPropertyId.FromString(name); var funcObj = JavaScriptValue.CreateFunction(func); JavaScriptValue.GlobalObject.SetProperty(funcName, funcObj, true); } }
/// <summary> /// This method creates a new <see cref="JavaScriptValue"/> representing a JavaScript function, and /// performs the binding of the resulting function with the native host function. /// </summary> /// <param name="func">The host function used to create the JavaScript function and binding.</param> /// <param name="instanceData">A pointer to the instance data that shoukld be passed on each execution of the instance.</param> public JavaScriptValue BindInstanceFunction(JavaScriptNativeFunction func, IntPtr instanceData) { return(_scope.Run(() => { var jsValue = JavaScriptValue.CreateFunction(func, instanceData); return jsValue; })); }
private void DefineCallback (JavaScriptValue hostObject, string callbackName, JavaScriptNativeFunction callbackDelegate) { var propertyId = JavaScriptPropertyId.FromString(callbackName); var function = JavaScriptValue.CreateFunction(callbackDelegate); hostObject.SetProperty(propertyId, function, true); }
private void InitializeChakra() { JavaScriptContext.Current = _runtime.CreateContext(); _nativeLoggingHook = NativeLoggingHook; EnsureGlobalObject().SetProperty( JavaScriptPropertyId.FromString("nativeLoggingHook"), JavaScriptValue.CreateFunction(_nativeLoggingHook), true); }
private static void DefineHostCallback( JavaScriptValue obj, string callbackName, JavaScriptNativeFunction callback) { var propertyId = JavaScriptPropertyId.FromString(callbackName); var function = JavaScriptValue.CreateFunction(callback); obj.SetProperty(propertyId, function, true); }
/// <summary> /// This method creates a new <see cref="JavaScriptValue"/> representing a JavaScript function, and /// performs the binding of the resulting function with the native host function. This ensures that the /// host function will not be garbage collected as long as the JavaScript function has not been garbage /// collected. /// </summary> /// <param name="func">The host function used to create the JavaScript function and binding.</param> public JavaScriptValue BindFunction(JavaScriptNativeFunction func) { return(_scope.Run(() => { var jsFunc = JsSafeDecorator.Decorate(func); var jsValue = JavaScriptValue.CreateFunction(jsFunc); Link(jsValue, jsFunc); return jsValue; })); }
private void DefineHostCallback(JavaScriptValue globalObject, string callbackName, JavaScriptNativeFunction callback, IntPtr callbackData) { // Get property ID. JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString(callbackName); // Create a function JavaScriptValue function = JavaScriptValue.CreateFunction(callback, callbackData); // Set the property globalObject.SetProperty(propertyId, function, true); }
// Example: Map the CLR objects to NanUI's JavaScript context. private void MapClrObjectToJavaScript() { var obj = JavaScriptValue.CreateObject(); // Readonly property obj.SetValue("now", JavaScriptValue.CreateProperty(() => { return(JavaScriptValue.CreateDateTime(DateTime.Now)); })); // Value obj.SetValue("version", JavaScriptValue.CreateString(Assembly.GetExecutingAssembly().GetName().Version?.ToString())); // Readable and writable property obj.SetValue("subtitle", JavaScriptValue.CreateProperty(() => JavaScriptValue.CreateString(Subtitle), title => Subtitle = title.GetString())); // Sync method obj.SetValue("messagebox", JavaScriptValue.CreateFunction(args => { var msg = args.FirstOrDefault(x => x.IsString); var text = msg?.GetString(); InvokeIfRequired(() => { MessageBox.Show(HostWindow, text, "Message from JS", MessageBoxButtons.OK, MessageBoxIcon.Information); }); return(JavaScriptValue.CreateString(text)); })); // Async method obj.SetValue("asyncmethod", JavaScriptValue.CreateFunction((args, callback) => { Task.Run(async() => { var rnd = new Random(DateTime.Now.Millisecond); var rndValue = rnd.Next(1000, 2000); await Task.Delay(rndValue); var obj = JavaScriptValue.CreateObject(); obj.SetValue("delayed", JavaScriptValue.CreateNumber(rndValue)); obj.SetValue("message", JavaScriptValue.CreateString($"Delayed {rndValue} milliseconds")); callback.Success(obj); }); })); RegisterExternalObjectValue("tester", obj); }
GenericWrapper(Type type) { this.type = type; if (!type.IsGenericTypeDefinition) { throw new ChakraSharpException("Generic definition only"); } thisPtr = GCHandle.Alloc(this); mainValueSrc = body; mainValue = JavaScriptValue.CreateFunction(mainValueSrc, GCHandle.ToIntPtr(thisPtr)); mainValue.AddRef(); }
public static JavaScriptValue JsConstructor(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData) { if (!isConstructCall) { return(JavaScriptValue.Invalid); } IntPtr objId; do { objId = new IntPtr(new Random().Next()); } while(instances.ContainsKey(objId)); var jsObj = JavaScriptValue.CreateExternalObject(objId, null); var actualObj = new JsXmlHttpRequest(jsObj); instances.Add(objId, actualObj); // Properties jsObj.SetProperty(JavaScriptPropertyId.FromString("readyState"), JavaScriptValue.FromInt32((int)ReadyStates.Unsent), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("response"), JavaScriptValue.FromString(""), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("responseText"), JavaScriptValue.FromString(""), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("responseType"), JavaScriptValue.FromString(""), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("responseUrl"), JavaScriptValue.FromString(""), true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("responseXML"), JavaScriptValue.Null, true); jsObj.SetProperty(JavaScriptPropertyId.FromString("status"), JavaScriptValue.FromInt32(0), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("statusText"), JavaScriptValue.FromString(""), true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("timeout"), JavaScriptValue.FromInt32(0), true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("upload"), JavaScriptValue.Null, true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("withCredentials"), JavaScriptValue.FromBoolean(false), true); // Event properties //jsObj.SetProperty(JavaScriptPropertyId.FromString("onabort"), JavaScriptValue.Null, true); jsObj.SetProperty(JavaScriptPropertyId.FromString("onerror"), JavaScriptValue.Null, true); jsObj.SetProperty(JavaScriptPropertyId.FromString("onload"), JavaScriptValue.Null, true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("onloadstart"), JavaScriptValue.Null, true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("onprogress"), JavaScriptValue.Null, true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("ontimeout"), JavaScriptValue.Null, true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("onloadend"), JavaScriptValue.Null, true); jsObj.SetProperty(JavaScriptPropertyId.FromString("onreadystatechange"), JavaScriptValue.Null, true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("ontimeout"), JavaScriptValue.Null, true); // Methods //jsObj.SetProperty(JavaScriptPropertyId.FromString("abort"), JavaScriptValue.CreateFunction(functions["abort"]), true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("getAllResponseHeaders"), JavaScriptValue.CreateFunction(functions["getAllResponseHeaders"]), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("open"), JavaScriptValue.CreateFunction(functions["open"]), true); //jsObj.SetProperty(JavaScriptPropertyId.FromString("overrideMimeType"), JavaScriptValue.CreateFunction(functions["overrideMimeType"]), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("send"), JavaScriptValue.CreateFunction(functions["send"]), true); jsObj.SetProperty(JavaScriptPropertyId.FromString("setRequestHeader"), JavaScriptValue.CreateFunction(functions["setRequestHeader"]), true); return(jsObj); }
private void DefineHostCallback( JavaScriptValue globalObject, string callbackName, JavaScriptNativeFunction callback, IntPtr callbackData) { var propertyId = JavaScriptPropertyId.FromString(callbackName); this.handles.Add(callback); var function = JavaScriptValue.CreateFunction(callback, callbackData); globalObject.SetProperty(propertyId, function, true); }
public JavaScriptValue GetJavaScriptValue() { if (!thisPtr.IsAllocated) { thisPtr = GCHandle.Alloc(this); } if (!jsvalue.IsValid) { jsvalueSrc = Wrap(); jsvalue = JavaScriptValue.CreateFunction(jsvalueSrc, GCHandle.ToIntPtr(thisPtr)); jsvalue.AddRef(); } return(jsvalue); }
public static void Set(PanelRenderer renderer = null) { Native.JsGetGlobalObject(out var globalObject); globalObject.SetProperty(JavaScriptPropertyId.FromString("global"), globalObject, true); SetConsoleLogObject(globalObject); if (renderer != null) { globalObject.SetProperty( JavaScriptPropertyId.FromString("__HOSTCONFIG__"), HostConfig.Create(), true); globalObject.SetProperty( JavaScriptPropertyId.FromString("__CONTAINER__"), renderer.visualTree.ToJavaScriptValue(), true); } var customFunctions = AppDomain.CurrentDomain.GetAssemblies() .Where(e => e.GetName().Name == "ReactUIElements" || e.GetReferencedAssemblies().Any(a => a.Name == "ReactUIElements")) .SelectMany(e => e.DefinedTypes) .SelectMany(e => e.GetMethods()) .Where(e => e.GetCustomAttribute <GlobalFunctionAttribute>() != null) .Select(e => new { attribute = e.GetCustomAttribute <GlobalFunctionAttribute>(), method = e }) .ToList(); foreach (var customFunction in customFunctions) { if (!ValidateFunctionMethod(customFunction.method)) { Debug.Log("Custom global method must have the following signature static JavaScriptValue Function(JavaScriptValue callee, bool isconstructcall, JavaScriptValue[] arguments, ushort argumentcount, IntPtr callbackdata)"); continue; } var function = JavaScriptValue.CreateFunction(customFunction.attribute.Name, (JavaScriptNativeFunction)customFunction.method.CreateDelegate(typeof(JavaScriptNativeFunction))); globalObject.SetProperty( JavaScriptPropertyId.FromString(customFunction.attribute.Name), function, true); } }
// Add methods for demo object in Formium.external object in JavaScript context. private void RegisterDemoWindowlObject() { var demoWindow = JavaScriptValue.CreateObject(); const string GITHUB_URL = "https://github.com/NetDimension/NanUI"; demoWindow.SetValue("openLicenseWindow", JavaScriptValue.CreateFunction(args => { InvokeIfRequired(() => { ShowAboutDialog(); }); return(null); })); demoWindow.SetValue("navigateToGitHub", JavaScriptValue.CreateFunction(args => { InvokeIfRequired(() => { OpenExternalUrl(GITHUB_URL); }); return(null); })); demoWindow.SetValue("openDevTools", JavaScriptValue.CreateFunction(args => { InvokeIfRequired(() => { ShowDevTools(); }); return(null); })); demoWindow.SetValue("openLocalFileResourceFolder", JavaScriptValue.CreateFunction(args => { InvokeIfRequired(() => { OpenExternalUrl(System.IO.Path.Combine(Application.StartupPath, "LocalFiles")); }); return(null); })); RegisterExternalObjectValue("demo", demoWindow); }
private Task <JavaScriptValue> ConvertPromiseToTask(JavaScriptValue promise) { // Get the 'then' function from the promise. var thenFunction = promise.GetProperty(JavaScriptPropertyId.FromString("then")); // Create resolve & reject callbacks and wire them to a TaskCompletionSource JavaScriptNativeFunction[] state = new JavaScriptNativeFunction[2]; TaskCompletionSource <JavaScriptValue> completion = new TaskCompletionSource <JavaScriptValue>(state); var resolveFunc = JavaScriptValue.CreateFunction( state[0] = (callee, call, arguments, count, data) => { if (count > 1) { completion.TrySetResult(arguments[1]); } else { completion.TrySetResult(JavaScriptValue.Undefined); } return(JavaScriptValue.Invalid); }); var rejectFunc = JavaScriptValue.CreateFunction( state[1] = (callee, call, arguments, count, data) => { if (count > 1) { completion.TrySetException(new JavaScriptException(arguments[1])); } else { completion.TrySetException( new JavaScriptException(JavaScriptValue.FromString("Unknown exception in JavaScript promise rejection."))); } return(JavaScriptValue.Invalid); }); // Register the callbacks with the promise using the 'then' function. thenFunction.CallFunction(promise, resolveFunc, rejectFunc); // Return a task which will complete when the promise completes. return(completion.Task); }
private void DefineHostCallback( JavaScriptValue globalObject, string callbackName, AsyncJavaScriptNativeFunction callback, // Note: this one is async IntPtr callbackData) { var propertyId = JavaScriptPropertyId.FromString(callbackName); // Create a promise-returning function from our Task-returning function. JavaScriptNativeFunction nativeFunction = (callee, call, arguments, count, data) => this.jsTaskScheduler.CreatePromise( callback(callee, call, arguments, count, data)); this.handles.Add(nativeFunction); var function = JavaScriptValue.CreateFunction( nativeFunction, callbackData); globalObject.SetProperty(propertyId, function, true); }
public JavaScriptValue GetJavaScriptValue() { if (!value.IsValid) { if (isType) { typeWrapper = TypeWrapper.Wrap(type); value = typeWrapper.GetJavaScriptValue(); } else { value = JavaScriptValue.CreateObject(); value.SetIndexedProperty(JavaScriptValue.FromString("toString"), JavaScriptValue.CreateFunction(InternalUtil.GetSavedStringDg, GCHandle.ToIntPtr(GCHandle.Alloc(path)))); } value.AddRef(); AssignToObject(value); } return(value); }
void AssignFieldProc(JavaScriptValue setTo, FieldInfo[] fields) { var getpropid = JavaScriptPropertyId.FromString("get"); var setpropid = JavaScriptPropertyId.FromString("set"); foreach (var f in fields) { if (f.IsSpecialName) { continue; } var desc = JavaScriptValue.CreateObject(); var id = JavaScriptPropertyId.FromString(f.Name); var proxy = new FieldProxy(f); desc.SetProperty(getpropid, JavaScriptValue.CreateFunction(FieldProxy.FieldGetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); desc.SetProperty(setpropid, JavaScriptValue.CreateFunction(FieldProxy.FieldSetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); setTo.DefineProperty(id, desc); fieldWrappers.Add(proxy); } }
void AssignPropertyProc(JavaScriptValue setTo, PropertyInfo[] props) { var getpropid = JavaScriptPropertyId.FromString("get"); var setpropid = JavaScriptPropertyId.FromString("set"); foreach (var info in props) { if (info.IsSpecialName) { continue; } var desc = JavaScriptValue.CreateObject(); var id = JavaScriptPropertyId.FromString(info.Name); var proxy = new PropertyProxy(info); desc.SetProperty(getpropid, JavaScriptValue.CreateFunction(PropertyProxy.PropertyGetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); desc.SetProperty(setpropid, JavaScriptValue.CreateFunction(PropertyProxy.PropertySetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); setTo.DefineProperty(id, desc); propertyWrappers.Add(proxy); } }
void AssignToObject(JavaScriptValue obj) { if (children == null) { return; } var getpropid = JavaScriptPropertyId.FromString("get"); var setpropid = JavaScriptPropertyId.FromString("set"); foreach (var kv in children) { var n = kv.Value; var t = n.type; var prop = JavaScriptPropertyId.FromString(n.name); var desc = JavaScriptValue.CreateObject(); var proxy = new PropertyProxy(n); propertyProxies.Add(proxy); desc.SetProperty(getpropid, JavaScriptValue.CreateFunction(PropertyProxy.PropertyGetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); desc.SetProperty(setpropid, JavaScriptValue.CreateFunction(PropertyProxy.PropertySetterDg, GCHandle.ToIntPtr(proxy.thisPtr)), true); obj.DefineProperty(prop, desc); } }
public static JavaScriptValue CreateAndExecute(JavaScriptValue callee, bool isconstructcall, JavaScriptValue[] arguments, ushort argumentcount, IntPtr callbackdata) { var callback = arguments[1]; var system = World.DefaultGameObjectInjectionWorld.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem>(); var buffer = system.CreateCommandBuffer(); var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); var ptr = GCHandle.ToIntPtr(handle); var jsBuffer = JavaScriptValue.CreateExternalObject(ptr, Finalizer); var jsBufferPrototype = JavaScriptValue.CreateObject(); jsBufferPrototype.SetProperty( JavaScriptPropertyId.FromString("createEntity"), JavaScriptValue.CreateFunction("createEntity", CreateEntity), true); jsBufferPrototype.SetProperty( JavaScriptPropertyId.FromString("setComponent"), JavaScriptValue.CreateFunction("setComponent", SetComponent), true); jsBufferPrototype.SetProperty( JavaScriptPropertyId.FromString("destroyEntity"), JavaScriptValue.CreateFunction("destroyEntity", DestroyEntity), true); jsBuffer.Prototype = jsBufferPrototype; try { callback.CallFunction(JavaScriptValue.Undefined, jsBuffer); } catch (Exception ex) { Debug.LogError(ex); } handle.Free(); return(JavaScriptValue.Undefined); }