/// <summary>
        /// Get the value of a named property.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="returnValue"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool GetProperty(string name, out CefV8Value returnValue, out string exception)
        {
            exception   = null;
            returnValue = null;

            if (string.IsNullOrEmpty(name))
            {
                exception = "No property name specified";
                return(false);
            }

            if (_expandoProperties.TryGetValue(name, out returnValue))
            {
                return(true);
            }

            try
            {
                object val;
                if (OnGetProperty(name, out val))
                {
                    returnValue = CefNativeValueConverter.ToCef(val);
                    return(true);
                }

                exception   = "Property not found: " + name;
                returnValue = CefV8Value.CreateUndefined();
                return(false);
            }
            catch (Exception ex)
            {
                exception = ex.Message;
                return(false);
            }
        }
 public void Test_GetSimpleValue_Undefined()
 {
     Test(() =>
     {
         object res = null;
         bool ok    = _CefV8_Converter.GetSimpleValue(CefV8Value.CreateUndefined().Convert(), out res);
         ok.Should().BeTrue();
         res.Should().Be(null);
     });
 }
Example #3
0
        public PromiseTask(
            CefV8Context ctx,
            CefV8Value resolveCb, CefV8Value rejectCb)
        {
            this.ctx       = ctx;
            this.resolveCb = resolveCb;
            this.rejectCb  = rejectCb;

            this.toRun  = CefV8Value.CreateUndefined();
            this.result = CefV8Value.CreateUndefined();
        }
Example #4
0
 public static CefV8Value ConvertToV8Value(object o)
 {
     if (o == null)
     {
         return(CefV8Value.CreateUndefined());
     }
     if (o is bool)
     {
         return(CefV8Value.CreateBool((bool)o));
     }
     if (o is DateTime)
     {
         return(CefV8Value.CreateDate((DateTime)o));
     }
     if (o is double)
     {
         return(CefV8Value.CreateDouble((double)o));
     }
     if (o is int)
     {
         return(CefV8Value.CreateInt((int)o));
     }
     if (o is string)
     {
         return(CefV8Value.CreateString((string)o));
     }
     if (o is uint)
     {
         return(CefV8Value.CreateUInt((uint)o));
     }
     if (o is Array)
     {
         var a   = (Array)o;
         var rtn = CefV8Value.CreateArray(a.Length);
         for (int i = 0; i < a.Length; i++)
         {
             rtn.SetValue(i, ConvertToV8Value(a.GetValue(i)));
         }
         return(rtn);
     }
     if (o is System.Collections.IList)
     {
         var a   = (System.Collections.IList)o;
         var rtn = CefV8Value.CreateArray(a.Count);
         for (int i = 0; i < a.Count; i++)
         {
             rtn.SetValue(i, ConvertToV8Value(a[i]));
         }
         return(rtn);
     }
     throw new NotSupportedException("??");
 }
        internal static CefV8Value CastCefValueToCefV8Value(CefV8Context context, CefValue value, out bool isNew)
        {
            isNew = true;

            if (value is null)
            {
                return(CefV8Value.CreateNull());
            }

            if (!value.IsValid)
            {
                throw new InvalidCastException();
            }

            CefValueType valueType = value.Type;

            switch (valueType)
            {
            case CefValueType.String:
                return(new CefV8Value(value.GetString()));

            case CefValueType.Int:
                return(new CefV8Value(value.GetInt()));

            case CefValueType.Bool:
                return(new CefV8Value(value.GetBool()));

            case CefValueType.Null:
                return(CefV8Value.CreateNull());

            case CefValueType.Double:
                return(new CefV8Value(value.GetDouble()));

            case CefValueType.Binary:
                CefBinaryValue v = value.GetBinary();
                if (v.Size == 1)
                {
                    return(CefV8Value.CreateUndefined());
                }

                XrayHandle handle = XrayHandle.FromCfxBinaryValue(v);
                if (handle == XrayHandle.Zero)
                {
                    return(context.GetGlobal());
                }

                isNew = (handle.dataType != XrayDataType.Object && handle.dataType != XrayDataType.Function);
                return(handle.ToCefV8Value(context.Frame));
            }

            throw new NotSupportedException();
        }
Example #6
0
 public static Task <CefV8Value> InvokeAsync(this CefV8Value @this, string functionname, IWebView context, params CefV8Value[] args)
 {
     return(context.EvaluateAsync(() =>
     {
         var fn = @this.GetValue(functionname);
         if ((fn == null) || !fn.IsFunction)
         {
             return CefV8Value.CreateUndefined();
         }
         return fn.ExecuteFunction(@this, args);
     }
                                  ));
 }
        protected override bool Get(string name, CefV8Value obj, out CefV8Value returnValue, out string exception)
        {
            var objectUserData = obj.GetUserData() as V8PluginAdapter;
            var scriptObject   = objectUserData != null ? objectUserData.Plugin : null;

            if (scriptObject != null)
            {
                return(scriptObject.GetProperty(name, out returnValue, out exception));
            }

            exception   = null;
            returnValue = CefV8Value.CreateUndefined();
            return(false);
        }
Example #8
0
        public static CefV8Value CreateValue(object value)
        {
            if (value == null)
            {
                return(CefV8Value.CreateNull());
            }
            if (value is bool)
            {
                return(CefV8Value.CreateBool((bool)value));
            }
            if (value is double)
            {
                return(CefV8Value.CreateDouble((double)value));
            }
            if (value is float)
            {
                return(CefV8Value.CreateDouble((double)(float)value));
            }
            if (value is int)
            {
                return(CefV8Value.CreateInt((int)value));
            }
            var s = value as string;

            if (s != null)
            {
                return(CefV8Value.CreateString(s));
            }
            if (value is uint)
            {
                return(CefV8Value.CreateUInt((uint)value));
            }
            var list = value as IList;

            if (list == null)
            {
                return(CefV8Value.CreateUndefined());
            }
            var val = list;

            var arr = CefV8Value.CreateArray(val.Count);

            for (var i = 0; i < val.Count; i++)
            {
                arr.SetValue(i, CreateValue(val[i]));
            }

            return(arr);
        }
Example #9
0
        /// <summary>
        /// Start executing the promise worker on a thread pool thread.
        /// </summary>
        /// <param name="arguments">The two callback provided by the JS side, one for resolving
        /// and one for rejecting the JS Promise.
        /// </param>
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            var resolveCb = arguments[0];
            var rejectCb  = arguments[1];

            var ctx         = CefV8Context.GetCurrentContext();
            var promiseTask = new PromiseTask(ctx, resolveCb, rejectCb);

            DoAsyncWork(ctx, promiseTask);

            // A fulfiller function doesn't return anything -- it's equivalent to
            // a 'void' C# function, so return 'undefined' to JS side.
            returnValue = CefV8Value.CreateUndefined();
            exception   = null !;
            return(true);
        }
Example #10
0
 private static CefV8Value Execute(this CefV8Value @this, string functionname, params CefV8Value[] args)
 {
     try
     {
         var fn = @this.GetValue(functionname);
         if ((fn == null) || !fn.IsFunction)
         {
             return(CefV8Value.CreateUndefined());
         }
         return(fn.ExecuteFunction(@this, args));
     }
     catch (Exception)
     {
         return(CefV8Value.CreateUndefined());
     }
 }
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            exception   = "";
            returnValue = CefV8Value.CreateUndefined();

            if (name == BroadcastMessageFunctionName)
            {
                if (arguments.Length > 0)
                {
                    if (BroadcastMessage != null)
                    {
                        BroadcastMessage(obj, new BroadcastMessageEventArgs(arguments[0].GetStringValue()));
                    }
                }
                else
                {
                    exception = "Invalid argument count.";
                }

                return(true);
            }
            else if (name == SendMessageFunctionName)
            {
                if (arguments.Length > 1)
                {
                    if (SendMessage != null)
                    {
                        SendMessage(obj, new SendMessageEventArgs(arguments[0].GetStringValue(), arguments[1].GetStringValue()));
                    }
                }
                else
                {
                    exception = "Invalid argument count.";
                }

                return(true);
            }
            else if (name == EndEncounterFunctionName)
            {
                if (EndEncounter != null)
                {
                    EndEncounter(obj, new EndEncounterEventArgs());
                }
            }

            return(false);
        }
        internal static CefV8Value CastDotnetTypeToCefV8Value(CefV8Context context, object value, out bool isNew)
        {
            isNew = true;

            if (value is null)
            {
                return(CefV8Value.CreateNull());
            }

            if (value is V8Undefined)
            {
                return(CefV8Value.CreateUndefined());
            }

            switch (value)
            {
            case string v:
                return(new CefV8Value(v));

            case int v:
                return(new CefV8Value(v));

            case double v:
                return(new CefV8Value(v));

            case bool v:
                return(new CefV8Value(v));

            case DateTime v:
                return(new CefV8Value(v));

            case XrayHandle v:
                isNew = (v.dataType != XrayDataType.Object && v.dataType != XrayDataType.Function);
                return(v.ToCefV8Value(context.Frame));

            case ScriptableObject v:
                XrayHandle hv = (XrayHandle)v;
                isNew = (hv.dataType != XrayDataType.Object && hv.dataType != XrayDataType.Function);
                CefV8Value cv8 = hv.ToCefV8Value(context.Frame);
                GC.KeepAlive(v);
                return(cv8);
            }

            throw new NotImplementedException("Type: " + value.GetType().Name);
        }
Example #13
0
        public static CefV8Value CreateValue(object value)
        {
            if (value == null)
            {
                return(CefV8Value.CreateNull());
            }
            if (value is bool)
            {
                return(CefV8Value.CreateBool((bool)value));
            }
            if (value is double)
            {
                return(CefV8Value.CreateDouble((double)value));
            }
            if (value is float)
            {
                return(CefV8Value.CreateDouble((double)(float)value));
            }
            if (value is int)
            {
                return(CefV8Value.CreateInt((int)value));
            }
            if (value is string)
            {
                return(CefV8Value.CreateString((string)value));
            }
            if (value is uint)
            {
                return(CefV8Value.CreateUInt((uint)value));
            }
            if (value is IList)
            {
                IList val = (IList)value;

                var arr = CefV8Value.CreateArray(val.Count);

                for (int i = 0; i < val.Count; i++)
                {
                    arr.SetValue(i, CreateValue(val[i]));
                }

                return(arr);
            }
            return(CefV8Value.CreateUndefined());
        }
        /// <summary>
        /// Handle execution of the function identified by |name|. |object| is the
        /// receiver ('this' object) of the function. |arguments| is the list of
        /// arguments passed to the function. If execution succeeds set |retval| to the
        /// function return value. If execution fails set |exception| to the exception
        /// that will be thrown. Return true if execution was handled.
        /// </summary>
        /// <param name="name">The name of the function to execute.</param>
        /// <param name="obj">The receiver ('this' object) of the function.</param>
        /// <param name="arguments">The list of arguments passed to the function</param>
        /// <param name="returnValue">If execution succeeds set |retval| to the function return value.</param>
        /// <param name="exception">If execution fails set |exception| to the exception that will be thrown.</param>
        /// <returns>Return true if execution was handled.</returns>
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            exception   = null;
            returnValue = null;

            try
            {
                if (!string.IsNullOrEmpty(name))
                {
                    var methodDescriptor = _plugin.Descriptor.Methods.Find(descriptor => descriptor.MethodName == name);
                    if (methodDescriptor == null)
                    {
                        Logger.Error("Plugin method {0} {1} not found", _plugin.Descriptor.PluginId, name);
                        return(false);
                    }

                    var context = CefV8Context.GetCurrentContext();

                    var v8Callback = arguments != null && arguments.Length != 0 && arguments[arguments.Length - 1].IsFunction
                        ? arguments[arguments.Length - 1]
                        : null;
                    var parameters = v8Callback != null?arguments.Take(arguments.Length - 1).ToArray() : arguments;

                    _plugin.ExecuteFunction(context, name, parameters, v8Callback, out returnValue, out exception);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Execution of plugin method {0} {1} failed: {2}", _plugin.Descriptor.PluginId, name, ex);
                exception = ex.Message;
            }

            returnValue = CefV8Value.CreateUndefined();

            return(false);
        }
Example #15
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            try
            {
                if (name == "Log")
                {
                    var message = arguments[0].GetStringValue();
                    #if DIAGNOSTICS
                    Cef.Logger.Info(LogTarget.Default, message);
                    #endif
                    returnValue = null;
                }
                else if (name == "ReturnVoid")
                {
                    returnValue = null;
                }
                else if (name == "ReturnVoidAndDisposeThis")
                {
                    returnValue = null;

                    if (obj != null)
                    {
                        obj.Dispose(); obj = null;
                    }
                }
                else if (name == "ReturnUndefined")
                {
                    returnValue = CefV8Value.CreateUndefined();
                }
                else if (name == "ReturnNull")
                {
                    returnValue = CefV8Value.CreateNull();
                }
                else if (name == "ReturnBool")
                {
                    returnValue = CefV8Value.CreateBool(true);
                }
                else if (name == "ReturnInt")
                {
                    returnValue = CefV8Value.CreateInt(12345678);
                }
                else if (name == "ReturnDouble")
                {
                    returnValue = CefV8Value.CreateDouble(1234.5678);
                }
                else if (name == "ReturnDate")
                {
                    returnValue = CefV8Value.CreateDate(DateTime.UtcNow);
                }
                else if (name == "ReturnString")
                {
                    returnValue = CefV8Value.CreateString("Some string, passed to CEF!");
                }
                else if (name == "ReturnArray")
                {
                    var array = CefV8Value.CreateArray(3);
                    array.SetValue(0, CefV8Value.CreateInt(123));
                    array.SetValue(1, CefV8Value.CreateString("hello!"));
                    array.SetValue(2, CefV8Value.CreateBool(false));

                    returnValue = array;
                }
                else if (name == "ReturnObject")
                {
                    var obj1 = CefV8Value.CreateObject();
                    obj1.SetValue("index", CefV8Value.CreateInt(123));
                    obj1.SetValue("reply", CefV8Value.CreateString("hello!"));
                    obj1.SetValue("success", CefV8Value.CreateBool(false));

                    returnValue = obj1;
                }
                else if (name == "ReturnComplexArray")
                {
                    var obj1 = CefV8Value.CreateObject();
                    obj1.SetValue("index", CefV8Value.CreateInt(123));
                    obj1.SetValue("reply", CefV8Value.CreateString("hello!"));
                    obj1.SetValue("success", CefV8Value.CreateBool(false));

                    var array = CefV8Value.CreateArray(5);
                    array.SetValue(0, CefV8Value.CreateInt(123));
                    array.SetValue(1, CefV8Value.CreateString("hello!"));
                    array.SetValue(2, CefV8Value.CreateBool(false));
                    array.SetValue(3, obj1);
                    array.SetValue(4, CefV8Value.CreateString("hello2!"));

                    obj1 = CefV8Value.CreateObject();
                    obj1.SetValue("index", CefV8Value.CreateInt(123));
                    obj1.SetValue("reply", CefV8Value.CreateString("hello!"));
                    obj1.SetValue("success", CefV8Value.CreateBool(false));

                    var obj2 = CefV8Value.CreateObject();
                    obj2.SetValue("i'm still", CefV8Value.CreateString("alive"));

                    obj1.SetValue("inner", obj2);

                    array.SetValue(5, obj1);

                    returnValue = array;
                }
                else if (name == "ReturnComplexObject")
                {
                    var obj1 = CefV8Value.CreateObject();
                    obj1.SetValue("index", CefV8Value.CreateInt(123));
                    obj1.SetValue("reply", CefV8Value.CreateString("hello!"));
                    obj1.SetValue("success", CefV8Value.CreateBool(false));

                    var obj2 = CefV8Value.CreateObject();
                    obj2.SetValue("i'm still", CefV8Value.CreateString("alive"));

                    obj1.SetValue("inner", obj2);

                    obj2.Dispose(); // force to dispose object wrapper and underlying v8 persistent handle.
                    // note, that obj2 will passed in obj before, but it anyway safe to destroy obj2 handle,
                    // 'cause v8 api internally always open handles.

                    returnValue = obj1;
                }
                else if (name == "SubtractIntImplicit")
                {
                    var a = arguments[0].GetIntValue();
                    var b = arguments[1].GetIntValue();

                    returnValue = CefV8Value.CreateInt(a - b);
                }
                else if (name == "SubtractIntExplicit")
                {
                    if (!arguments[0].IsInt)
                    {
                        throw new ArgumentException("arg0");
                    }
                    var a = arguments[0].GetIntValue();

                    if (!arguments[1].IsInt)
                    {
                        throw new ArgumentException("arg1");
                    }
                    var b = arguments[1].GetIntValue();

                    returnValue = CefV8Value.CreateInt(a - b);
                }
                else if (name == "Dump")
                {
                    returnValue = CefV8Value.CreateString(Dump(arguments));
                }
                else if (name == "get_PrivateWorkingSet")
                {
                    var result = Process.GetCurrentProcess().PrivateMemorySize64 / (1024.0 * 1024.0);
                    returnValue = CefV8Value.CreateDouble(result);
                }
                else if (name == "leakTestV8Func")
                {
                    var handler = new TestV8Handler();
                    for (var i = 0; i < 100000; i++)
                    {
                        var x = CefV8Value.CreateFunction("LeakTest", handler);
                        x.Dispose();
                    }
                    returnValue = CefV8Value.CreateBool(true);
                }
                else
                {
                    returnValue = null;
                    exception   = null;
                    return(false);
                }

                exception = null;
                return(true);
            }
            catch (Exception ex)
            {
                returnValue = null;
                exception   = ex.ToString();
                return(true);
            }
        }
        public static CefV8Value ToCef(JToken jsonToken)
        {
            switch (jsonToken.Type)
            {
            case JTokenType.Object:
            {
                var jObject     = (JObject)jsonToken;
                var plainObject = CefV8Value.CreateObject(null);
                foreach (var jsonProperty in jObject.Properties())
                {
                    plainObject.SetValue(jsonProperty.Name, ToCef(jsonProperty.Value), CefV8PropertyAttribute.None);
                }
                return(plainObject);
            }

            case JTokenType.Array:
            {
                var jArray     = (JArray)jsonToken;
                var arrayValue = CefV8Value.CreateArray(jArray.Count);
                for (var i = 0; i < jArray.Count; i++)
                {
                    arrayValue.SetValue(i, ToCef(jArray[i]));
                }
                return(arrayValue);
            }

            case JTokenType.Integer:
            {
                var jsonValue = (JValue)jsonToken;
                if (jsonValue.Value is long)
                {
                    return(CefV8Value.CreateDouble((double)jsonToken));
                }
                return(CefV8Value.CreateInt((int)jsonToken));
            }

            case JTokenType.Float:
                return(CefV8Value.CreateDouble((double)jsonToken));

            case JTokenType.Guid:
            case JTokenType.Uri:
            case JTokenType.String:
                return(CefV8Value.CreateString((string)jsonToken));

            case JTokenType.Boolean:
                return(CefV8Value.CreateBool((bool)jsonToken));

            case JTokenType.Null:
                return(CefV8Value.CreateNull());

            case JTokenType.Undefined:
                return(CefV8Value.CreateUndefined());

            case JTokenType.Date:
                return(CefV8Value.CreateDate((DateTime)jsonToken));

            case JTokenType.Raw:
            case JTokenType.Bytes:
            case JTokenType.TimeSpan:
            case JTokenType.Property:
            case JTokenType.Comment:
            case JTokenType.Constructor:
            case JTokenType.None:
                throw new NotSupportedException();

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            if (name == _name)
            {
                var bid = _context.GetBrowser()?.Identifier ?? 0;
                var fid = _context.GetFrame()?.Identifier ?? 0;

                var request = MessageBridgeRequest.Create(JavaScriptCommunicationBridge.EXECUTE_JAVASCRIPT_FUNCTION, bid, fid, _context.GetHashCode());

                request.Arguments.Add(MessageValue.CreateString(_parentKey));
                request.Arguments.Add(MessageValue.CreateString(_name));

                var args = JavaScriptValue.CreateArray();

                var index = 0;

                foreach (var arg in arguments)
                {
                    var value = arg.ToJSValue();

                    if (value != null)
                    {
                        args.SetValue(index++, value);
                    }
                }

                request.Arguments.Add(MessageValue.CreateString(args.ToDefinition()));

                var guid = Guid.NewGuid();

                request.Arguments.Add(MessageValue.CreateString($"{guid}"));

                var response = _bridge.SendExecutionRequest(request);

                if (response.IsSuccess)
                {
                    if (_functionInfo.IsAsync)
                    {
                        var callback = CefV8Value.CreateObject();

                        var successFunc = CefV8Value.CreateFunction("success", new JavaScriptBridgeFunctionCallbackHandler(/*_parentKey, _name,*/ guid, _context));

                        var errorFunc = CefV8Value.CreateFunction("error", new JavaScriptBridgeFunctionCallbackHandler(/*_parentKey, _name,*/ guid, _context));

                        callback.SetValue("success", successFunc);
                        callback.SetValue("error", errorFunc);

                        returnValue = callback;
                        exception   = null;
                    }
                    else
                    {
                        var retval = JavaScriptValue.FromJson(response.Arguments[0].GetString())?.ToCefV8Value();

                        exception = null;

                        if (retval != null)
                        {
                            returnValue = retval;
                        }
                        else
                        {
                            returnValue = CefV8Value.CreateUndefined();
                        }
                    }
                }
                else
                {
                    exception   = response.ExceptionMessage;
                    returnValue = null;
                }

                return(true);
            }

            returnValue = null;
            exception   = $"{name} is not defined.";

            return(true);
        }
Example #18
0
 public IJavascriptObject CreateUndefined()
 {
     return(new CefV8_JavascriptObject(CefV8Value.CreateUndefined()));
 }
Example #19
0
        /// <summary>
        /// Handle execution of the function identified by |name|. |object| is the
        /// receiver ('this' object) of the function. |arguments| is the list of
        /// arguments passed to the function. If execution succeeds set |retval| to the
        /// function return value. If execution fails set |exception| to the exception
        /// that will be thrown. Return true if execution was handled.
        /// </summary>
        /// <param name="name">The name of the function to execute.</param>
        /// <param name="obj">The receiver ('this' object) of the function.</param>
        /// <param name="arguments">The list of arguments passed to the function</param>
        /// <param name="returnValue">If execution succeeds set |retval| to the function return value.</param>
        /// <param name="exception">If execution fails set |exception| to the exception that will be thrown.</param>
        /// <returns>Return true if execution was handled.</returns>
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue,
                                        out string exception)
        {
            if (string.IsNullOrEmpty(name))
            {
                returnValue = CefV8Value.CreateUndefined();
                exception   = "Unknown event name";
                return(false);
            }

            exception   = null;
            returnValue = null;

            try
            {
                switch (name)
                {
                case MethodNameAddListener:
                case MethodNameRemoveListener:
                {
                    if (arguments == null || arguments.Length != 1 || !arguments[0].IsFunction)
                    {
                        exception = "Expected a callback as the only argument";
                    }
                    else
                    {
                        var context    = CefV8Context.GetCurrentContext();  // TODO should this be disposed?
                        var v8Callback = arguments[0];

                        switch (name)
                        {
                        case MethodNameAddListener:
                            _plugin.AddEventListener(context, _eventName, v8Callback);
                            break;

                        case MethodNameRemoveListener:
                            _plugin.RemoveEventListener(context, _eventName, v8Callback);
                            break;
                        }
                        return(true);
                    }
                    break;
                }

                case MethodNameHasListener:
                {
                    if (arguments == null || arguments.Length != 1 || !arguments[0].IsFunction)
                    {
                        exception = "Expected a callback as the only argument";
                    }
                    else
                    {
                        var v8Callback  = arguments[0];
                        var hasListener = _plugin.HasEventListener(_eventName, v8Callback);
                        returnValue = CefV8Value.CreateBool(hasListener);
                        return(true);
                    }
                    break;
                }

                case MethodNameHasListeners:
                {
                    var hasListener = _plugin.HasEventListeners(_eventName);
                    returnValue = CefV8Value.CreateBool(hasListener);
                    return(true);
                }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Execution of plugin event method {0} {1} {2} failed: {3}",
                             _plugin.Descriptor.PluginId,
                             _eventName,
                             name,
                             ex);

                exception = ex.Message;
            }

            returnValue = CefV8Value.CreateUndefined();
            return(false);
        }
        public static CefV8Value ToCef(object nativeObject, Type type)
        {
            if (nativeObject == null)
            {
                if (type != null && type == typeof(void))
                {
                    return(CefV8Value.CreateUndefined());
                }
                return(CefV8Value.CreateNull());
            }

            if (nativeObject is bool)
            {
                return(CefV8Value.CreateBool((bool)nativeObject));
            }

            var stringValue = nativeObject as string;

            if (stringValue != null)
            {
                return(CefV8Value.CreateString(stringValue));
            }

            if (nativeObject is int || nativeObject is byte ||
                nativeObject is ushort || nativeObject is sbyte ||
                nativeObject is short || nativeObject is char)
            {
                return(CefV8Value.CreateInt(Convert.ToInt32(nativeObject)));
            }

            if (nativeObject is double || nativeObject is decimal ||
                nativeObject is long || nativeObject is uint ||
                nativeObject is ulong || nativeObject is float)
            {
                return(CefV8Value.CreateDouble(Convert.ToDouble(nativeObject)));
            }

            var nativeArray = nativeObject as Array;

            if (nativeArray != null)
            {
                var cefArray = CefV8Value.CreateArray(nativeArray.Length);
                for (var i = 0; i < nativeArray.Length; i++)
                {
                    var nativeArrayItem = nativeArray.GetValue(i);
                    var cefArrayItem    = ToCef(nativeArrayItem, null);
                    cefArray.SetValue(i, cefArrayItem);
                }
                return(cefArray);
            }

            var jsonToken = nativeObject as JToken;

            if (jsonToken != null)
            {
                return(CefJsonValueConverter.ToCef(jsonToken));
            }

            if (type == null)
            {
                type = nativeObject.GetType();
            }

            var typeConverter = GetTypeConverter(type);

            if (typeConverter != null)
            {
                return(typeConverter.ToCef(nativeObject));
            }

            throw new Exception(string.Format("Cannot convert '{0}' object from CLR to CEF.", type.FullName));
        }
Example #21
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            var context = CefV8Context.GetCurrentContext();

            var browser = context.GetBrowser();

            var frame = browser.GetMainFrame();

            var function = Extension.FunctionHandlers.SingleOrDefault(x => x.FuntionName.Equals(name));

            //WinFormium.GetLogger().Debug($"{name}");

            if (function == null)
            {
                exception   = $"[NanUI]:{name} is not defined.";
                returnValue = null;


                return(true);
            }



            var args = JavaScriptValue.CreateArray();

            var index = 0;

            foreach (var arg in arguments)
            {
                var value = arg.ToJSValue();

                if (value != null)
                {
                    args.SetValue(index++, value);
                }
            }


            exception = null;

            var uuid = Guid.NewGuid();



            if (function.FunctionType == JavaScriptExtensionFunctionHandlerType.RendererSideFunction || function.FunctionType == JavaScriptExtensionFunctionHandlerType.RendererSideAsyncFunction)
            {
                if (function.FunctionType == JavaScriptExtensionFunctionHandlerType.RendererSideFunction)
                {
                    var retval = function.RendererSideFunction.Invoke(args.ToArray());
                    returnValue = retval?.ToCefV8Value() ?? CefV8Value.CreateUndefined();
                }
                else
                {
                    function.RendererSideAsyncFunction.Invoke(args.ToArray(), new JavaScriptRendererSideAsyncFunctionCallback(frame, uuid, JSBridge));

                    var callback    = CefV8Value.CreateObject();
                    var successFunc = CefV8Value.CreateFunction("success", new JavaScriptBridgeFunctionCallbackHandler(uuid, context));

                    var errorFunc = CefV8Value.CreateFunction("error", new JavaScriptBridgeFunctionCallbackHandler(uuid, context));


                    callback.SetValue("success", successFunc);
                    callback.SetValue("error", errorFunc);

                    returnValue = callback;
                }

                return(true);
            }
            else
            {
                var request = MessageBridgeRequest.Create(JavaScriptCommunicationBridge.EXECUTE_EXT_JAVASCRIPT_FUNCION, browser.Identifier, frame.Identifier, context.GetHashCode());


                request.Arguments.Add(MessageValue.CreateString(Extension.Name));

                request.Arguments.Add(MessageValue.CreateString(name));

                request.Arguments.Add(MessageValue.CreateString(args.ToDefinition()));

                request.Arguments.Add(MessageValue.CreateString($"{uuid}"));


                var response = JSBridge.SendExecutionRequest(request);



                if (response.IsSuccess)
                {
                    if (function.FunctionType == JavaScriptExtensionFunctionHandlerType.BrowserSideFunction)
                    {
                        if (response.Arguments != null && response.Arguments.Count > 0)
                        {
                            var retval = JavaScriptValue.FromJson(response.Arguments[0].GetString())?.ToCefV8Value();


                            if (retval != null)
                            {
                                returnValue = retval;
                                return(true);
                            }
                        }
                    }
                    else
                    {
                        var callback    = CefV8Value.CreateObject();
                        var successFunc = CefV8Value.CreateFunction("success", new JavaScriptBridgeFunctionCallbackHandler(uuid, context));

                        var errorFunc = CefV8Value.CreateFunction("error", new JavaScriptBridgeFunctionCallbackHandler(uuid, context));

                        callback.SetValue("success", successFunc);
                        callback.SetValue("error", errorFunc);

                        returnValue = callback;

                        return(true);
                    }

                    returnValue = CefV8Value.CreateUndefined();
                }
                else
                {
                    returnValue = null;
                    exception   = response.ExceptionMessage;
                }
            }

            return(true);
        }
Example #22
0
        public CefV8Value AsV8Value()
        {
            CefV8Value result = null;

            if (this.Value is IList)
            {
                var v = (IList)this.Value;

                result = CefV8Value.CreateArray(v.Count);

                for (var i = 0; i < v.Count; i++)
                {
                    result.SetValue(i, new JSValue(v[i]).AsV8Value());
                }
            }
            else if (this.Value is Boolean)
            {
                result = CefV8Value.CreateBool((Boolean)this.Value);
            }
            else if (this.Value is DateTime)
            {
                result = CefV8Value.CreateDate((DateTime)this.Value);
            }
            else if (this.Value is Single || this.Value is Double || this.Value is Decimal || this.Value is UInt64 || this.Value is Int64)
            {
                result = CefV8Value.CreateDouble((Double)this.Value);
            }
            else if (this.Value is CefV8Handler)
            {
                result = CefV8Value.CreateFunction(null, (CefV8Handler)this.Value);
            }
            else if (this.Value is SByte || this.Value is Int16 || this.Value is Int32)
            {
                result = CefV8Value.CreateInt((Int32)this.Value);
            }
            else if (this.Value == null)
            {
                result = CefV8Value.CreateNull();
            }
            else if (this.Value is IDictionary)
            {
                var v = (IDictionary)this.Value;

                Debug.Assert(v.Keys.Count == v.Values.Count);

                var vKeys   = new String[v.Keys.Count];
                var vValues = new CefV8Value[v.Values.Count];

                result = CefV8Value.CreateObject(null);

                for (var i = 0; i < vKeys.Length; i++)
                {
                    result.SetValue(vKeys[i], new JSValue(vValues[i]).AsV8Value(), CefV8PropertyAttribute.None);
                }
            }
            else if (this.Value is String)
            {
                result = CefV8Value.CreateString((String)this.Value);
            }
            else if (this.Value is Byte || this.Value is UInt16 || this.Value is UInt32)
            {
                result = CefV8Value.CreateUInt((UInt32)this.Value);
            }

            if (result == null)
            {
                result = CefV8Value.CreateUndefined();
            }

            return(result);
        }