Esempio n. 1
0
        public static CefV8Value ToCefV8Value(this JavaScriptValue source)
        {
            switch (source.ValueType)
            {
            case JavaScriptValueType.Null:
                return(CefV8Value.CreateNull());

            case JavaScriptValueType.Bool:
                return(CefV8Value.CreateBool(source.GetBool()));

            case JavaScriptValueType.Int:
                return(CefV8Value.CreateInt(source.GetInt()));

            case JavaScriptValueType.Double:
                return(CefV8Value.CreateDouble(source.GetDouble()));

            case JavaScriptValueType.String:
                return(CefV8Value.CreateString(source.GetString()));

            case JavaScriptValueType.DateTime:
                return(CefV8Value.CreateDate(source.GetDateTime()));

            case JavaScriptValueType.Property:
                break;

            case JavaScriptValueType.Function:
                break;

            case JavaScriptValueType.Object:
                var obj = CefV8Value.CreateObject();
                foreach (var key in source.Keys)
                {
                    var retval = source.GetValue(key)?.ToCefV8Value();
                    if (retval != null)
                    {
                        obj.SetValue(key, retval);
                    }
                }
                return(obj);

            case JavaScriptValueType.Array:
                var result = new List <CefV8Value>();
                for (int i = 0; i < source.ArrayLength; i++)
                {
                    var retval = source.GetValue(i)?.ToCefV8Value();
                    if (retval != null)
                    {
                        result.Add(retval);
                    }
                }
                var array = CefV8Value.CreateArray(result.Count);
                for (int i = 0; i < result.Count; i++)
                {
                    array.SetValue(i, result[i]);
                }
                return(array);
            }

            return(null);
        }
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "log" && arguments.Length > 0)
                {
                    var message = arguments[0].GetStringValue();
                    if (!string.IsNullOrEmpty(message))
                    {
                        Log.Trace(message.ToString(), true);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }
        public void SetCefValue(CefV8Value cefObject, object nativeObject)
        {
            var propertyValue = _propertyInfo.GetValue(nativeObject, null);
            var cefValue      = propertyValue != null
                ? CefNativeValueConverter.ToCef(propertyValue, _propertyInfo.PropertyType)
                : CefV8Value.CreateNull();

            cefObject.SetValue(MemberName, cefValue, CefV8PropertyAttribute.None);
        }
Esempio n. 4
0
        public void SetCefValue(CefV8Value cefObject, object nativeObject)
        {
            var fieldValue = _fieldInfo.GetValue(nativeObject);
            var cefValue   = fieldValue != null
                ? CefNativeValueConverter.ToCef(fieldValue, _fieldInfo.FieldType)
                : CefV8Value.CreateNull();

            cefObject.SetValue(MemberName, cefValue, CefV8PropertyAttribute.None);
        }
 public void Test_GetSimpleValue_Null()
 {
     Test(() =>
     {
         object res = null;
         bool ok    = _CefV8_Converter.GetSimpleValue(CefV8Value.CreateNull().Convert(), out res);
         ok.Should().BeTrue();
         res.Should().Be(null);
     });
 }
Esempio n. 6
0
        public static void RegisteredType(Type type, CefBrowser browser, CefFrame frame, CefV8Context context)
        {
            var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Static);

            foreach (var method in methods)
            {
                var parames = method.GetParameters();

                var function = new JSFunctionV8Handler();
                function.JSFunction = (string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) =>
                {
                    //有参数
                    if (parames != null && parames.Length > 0)
                    {
                        var agrs = new object[parames.Length];
                        for (int i = 0; i < parames.Length; i++)
                        {
                            object arg = null;
                            if (i < arguments.Length)
                            {
                                arg = CefV8ValueConvert(arguments[i]);
                            }

                            var param = parames[i];

                            //获取value的值
                            if (arg == null)
                            {
                                continue;
                            }
                            //如果参数类型不对
                            if (arg.GetType() != param.ParameterType)
                            {
                                continue;
                            }
                            agrs[i] = arg;
                        }
                        method.Invoke(null, agrs);
                    }
                    else
                    {
                        //无参数
                        method.Invoke(null, null);
                    }
                    exception   = null;
                    returnValue = CefV8Value.CreateNull();
                    return(true);
                };

                //绑定到context中去
                context.GetGlobal().SetValue(method.Name, CefV8Value.CreateFunction(method.Name, function), CefV8PropertyAttribute.DontDelete | CefV8PropertyAttribute.ReadOnly);
            }
        }
        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();
        }
Esempio n. 8
0
        public bool Execute(string name, ICefV8Value obj, ICefV8Value[] arguments, out ICefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;
            var result = false;

            if (name == "bindingRequire")
            {
                var browser = CefV8Context.GetCurrentContext().GetBrowser();

                if (browserControllers.TryGetValue(browser.Identifier, out var browserController))
                {
                    returnValue = browserController.OnBindingRequire(arguments[0]);
                }

                result = true;
            }
            else if (name == "setPromiseInteractions")
            {
                var context            = CefV8Context.GetCurrentContext();
                var global             = context.GetGlobal();
                var promiseDataStorage = CefV8Value.CreateObject();
                global.SetValue(PromiseService.HelperObjectName, promiseDataStorage,
                                CefV8PropertyAttribute.DontDelete | CefV8PropertyAttribute.DontEnum |
                                CefV8PropertyAttribute.ReadOnly);

                promiseDataStorage.SetUserData(new PromiseUserData(arguments[0], arguments[1], arguments[2]));

                result = true;
            }
            else if (name == "promiseDone")
            {
                using (var id = arguments[0])
                    using (var success = arguments[1])
                        using (var error = arguments[3])
                        {
                            var res = arguments[2];
                            PromiseResult?.Invoke(new PromiseResult
                            {
                                Id      = id.GetStringValue(),
                                Success = success.GetBoolValue(),
                                Error   = error.IsString ? error.GetStringValue() : null,
                                Result  = res,
                                Context = CefV8Context.GetCurrentContext()
                            });
                        }

                result = true;
            }

            return(result);
        }
Esempio n. 9
0
 public static CefV8Value ConvertToV8Value(dynamic result)
 {
     if (result != null)
     {
         if (result is bool)
         {
             return(CefV8Value.CreateBool(result));
         }
         else if (result is DateTime)
         {
             return(CefV8Value.CreateDate(result));
         }
         else if (result is double)
         {
             return(CefV8Value.CreateDouble(result));
         }
         else if (result is int)
         {
             return(CefV8Value.CreateInt(result));
         }
         else if (result is string)
         {
             return(CefV8Value.CreateString(result));
         }
         else if (result is uint)
         {
             return(CefV8Value.CreateUInt(result));
         }
         else if (result is Array)
         {
             var source      = (Array)result;
             var destination = CefV8Value.CreateArray(source.Length);
             for (int x = 0; x < source.Length; x++)
             {
                 destination.SetValue(x, ConvertToV8Value(source.GetValue(x)));
             }
             return(destination);
         }
         else if (result is System.Collections.IList)
         {
             var source      = (System.Collections.IList)result;
             var destination = CefV8Value.CreateArray(source.Count);
             for (int x = 0; x < source.Count; x++)
             {
                 destination.SetValue(x, ConvertToV8Value(source[x]));
             }
             return(destination);
         }
         //else throw new NotSupportedException("V8 Value");
     }
     return(CefV8Value.CreateNull());
 }
Esempio n. 10
0
 public static CefV8Value ConvertToJsValue(object?value)
 {
     if (value is null)
     {
         return(CefV8Value.CreateNull());
     }
     return(value switch
     {
         CefV8Value v => v,
         string s => CefV8Value.CreateString(s),
         bool b => CefV8Value.CreateBool(b),
         Exception ex => MakeJsRejection(ex),
         _ => throw new NotImplementedException()
     });
Esempio n. 11
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);
        }
Esempio n. 12
0
 /// <summary>
 /// Execute the delegated code synchronously.
 /// </summary>
 protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
 {
     try
     {
         var result = func.Method.Invoke(func.Target, arguments);
         returnValue = ValueConverter.ConvertToJsValue(result);
         exception   = null !;
     }
     catch (Exception ex)
     {
         returnValue = CefV8Value.CreateNull();
         exception   = ex.Message;
     }
     return(true);
 }
Esempio n. 13
0
        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);
        }
Esempio n. 14
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());
        }
Esempio n. 15
0
            protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = null;

                var args = ConvertArguments(arguments);

                if (this.owner != null && this.owner.Engine != null)
                {
                    if (name == "log")
                    {
                        this.owner.log(this.owner.Engine, false, this.owner, args);
                    }
                }

                //if (name == "log" && arguments.Length >= 1) log(arguments[0].GetStringValue());
                return(true);
            }
        private CefV8Value DontMeetRequirements(CefV8Context context, CefV8Value callback)
        {
            var msg = JsonMapper.ToJson(new StatusHelper("Error", "Arguments do not meet function requirement"));

            if (callback != null)
            {
                var runner = CefTaskRunner.GetForCurrentThread();
                new Task(() =>
                {
                    context.Enter();
                    runner.PostTask(new CallbackTask(context, callback, msg));
                    context.Exit();
                }).Start();
                return(CefV8Value.CreateNull());
            }
            else
            {
                return(CefV8Value.CreateString(msg));
            }
        }
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "query")
                {
                    if (arguments.Length >= 4)
                    {
                        var sql           = arguments[0].GetStringValue();
                        var connection    = arguments[1].GetStringValue();
                        var returntype    = arguments[2].GetStringValue();
                        var executionMode = arguments[3].GetStringValue();
                        var callback      = (arguments.Length == 5 ? arguments[4] : null);

                        if (!string.IsNullOrEmpty(sql) && !string.IsNullOrEmpty(connection) && !string.IsNullOrEmpty(returntype) && !string.IsNullOrEmpty(executionMode))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    runner.PostTask(new CallbackTask(context, callback, query(sql, connection, returntype, executionMode)));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                returnValue = CefV8Value.CreateString(query(sql, connection, returntype, executionMode));
                            }
                        }
                        else
                        {
                            returnValue = Extension.DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = Extension.DontMeetRequirements(context, null);
                    }
                }
                else if (name == "reader")
                {
                    if (arguments.Length >= 4)
                    {
                        var sql        = arguments[0].GetStringValue();
                        var connection = arguments[1].GetStringValue();
                        var returntype = arguments[2].GetStringValue();
                        var callback   = arguments[3];

                        if (!string.IsNullOrEmpty(sql) && !string.IsNullOrEmpty(connection) && !string.IsNullOrEmpty(returntype) && callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                try
                                {
                                    var db = new ConnectionHelper(connection);
                                    if (db != null)
                                    {
                                        db.Open();
                                        var cmd = db.CreateCommand(sql);
                                        if (cmd != null)
                                        {
                                            var dataReader = cmd.ExecuteReader();
                                            if (dataReader != null)
                                            {
                                                var hasData = dataReader.Read();
                                                if (!hasData)
                                                {
                                                    if (returntype.ToLower().Equals("json"))
                                                    {
                                                        var row = new Dictionary <string, object>();
                                                        runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(row)));
                                                    }
                                                    else if (returntype.ToLower().Equals("xml"))
                                                    {
                                                        var doc = new XElement("Item");
                                                        runner.PostTask(new CallbackTask(context, callback, doc.ToString()));
                                                    }
                                                }

                                                while (hasData)
                                                {
                                                    var columns = Enumerable.Range(0, dataReader.FieldCount()).Select(dataReader.GetName).ToList();
                                                    if (returntype.ToLower().Equals("json"))
                                                    {
                                                        while (dataReader.Read())
                                                        {
                                                            var row = new Dictionary <string, object>();
                                                            for (int x = 0; x < columns.Count; x++)
                                                            {
                                                                var column = columns[x];
                                                                row.Add(columns[x], Extension.ObjectToString(dataReader.GetValue(dataReader.GetOrdinal(column))));
                                                            }
                                                            runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(row)));
                                                        }
                                                    }
                                                    else if (returntype.ToLower().Equals("xml"))
                                                    {
                                                        while (dataReader.Read())
                                                        {
                                                            var row = new Dictionary <string, object>();
                                                            for (int x = 0; x < columns.Count; x++)
                                                            {
                                                                var column = columns[x];
                                                                row.Add(columns[x], Extension.ObjectToString(dataReader.GetValue(dataReader.GetOrdinal(column))));
                                                            }
                                                            var doc = new XElement("Item", row.Select(x => new XElement(x.Key, x.Value)));
                                                            runner.PostTask(new CallbackTask(context, callback, doc.ToString()));
                                                        }
                                                    }
                                                    hasData = dataReader.Read();
                                                }
                                                dataReader.Close();
                                            }
                                        }
                                        db.Close();
                                    }
                                    else
                                    {
                                        var msg = new StatusHelper("Error", "Failed to create database connection");
                                        runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(msg)));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    var msg = new StatusHelper("Error", ex.Message);
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(msg)));
                                }
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            returnValue = Extension.DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = Extension.DontMeetRequirements(context, null);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "compile" || name == "loadScript" || name == "loadScriptCompiled")
                {
                    if (arguments.Length >= 3)
                    {
                        var script                = arguments[0].GetStringValue();
                        var sourceName            = arguments[1].GetStringValue();
                        var throwExceptionOnError = arguments[2].GetBoolValue();
                        var callback              = (arguments.Length == 4 ? arguments[3] : null);

                        if (!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(sourceName))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    if (name == "compile")
                                    {
                                        engine.Compile(script, sourceName, throwExceptionOnError);
                                    }
                                    else if (name == "loadScript")
                                    {
                                        engine.LoadScript(script, sourceName, throwExceptionOnError);
                                    }
                                    else if (name == "loadScriptCompiled")
                                    {
                                        engine.LoadScriptCompiled(script, sourceName, throwExceptionOnError);
                                    }
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", name))));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                if (name == "compile")
                                {
                                    engine.Compile(script, sourceName, throwExceptionOnError);
                                }
                                else if (name == "loadScript")
                                {
                                    engine.LoadScript(script, sourceName, throwExceptionOnError);
                                }
                                else if (name == "loadScriptCompiled")
                                {
                                    engine.LoadScriptCompiled(script, sourceName, throwExceptionOnError);
                                }
                                returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", name)));
                            }
                        }
                        else
                        {
                            returnValue = DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    }
                }
                else if (name == "consoleExecute" || name == "execute" || name == "verboseConsoleExecute")
                {
                    if (arguments.Length >= 4)
                    {
                        var script                = arguments[0].GetStringValue();
                        var sourceName            = arguments[1].GetStringValue();
                        var throwExceptionOnError = arguments[2].GetBoolValue();
                        var timeOut               = arguments[3].GetIntValue();
                        var callback              = (arguments.Length == 5 ? arguments[4] : null);

                        if (!string.IsNullOrEmpty(script) && !string.IsNullOrEmpty(sourceName))
                        {
                            if (callback != null && callback.IsFunction)
                            {
                                var runner = CefTaskRunner.GetForCurrentThread();
                                new Task(() =>
                                {
                                    context.Enter();
                                    if (name == "consoleExecute")
                                    {
                                        engine.ConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    else if (name == "execute")
                                    {
                                        engine.Execute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    else if (name == "verboseConsoleExecute")
                                    {
                                        engine.VerboseConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                    }
                                    runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", name))));
                                    context.Exit();
                                }).Start();
                            }
                            else
                            {
                                if (name == "consoleExecute")
                                {
                                    engine.ConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                else if (name == "execute")
                                {
                                    engine.Execute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                else if (name == "verboseConsoleExecute")
                                {
                                    engine.VerboseConsoleExecute(script, sourceName, throwExceptionOnError, timeOut);
                                }
                                returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", name)));
                            }
                        }
                        else
                        {
                            returnValue = DontMeetRequirements(context, callback);
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    }
                }
                else if (name == "terminateExecution")
                {
                    if (arguments.Length >= 0)
                    {
                        var callback = (arguments.Length == 1 ? arguments[0] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                engine.TerminateExecution();
                                runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", "TerminateExecution"))));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            engine.TerminateExecution();
                            returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", "TerminateExecution")));
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    };
                }
                else if (name == "runStartupFile")
                {
                    if (arguments.Length >= 0)
                    {
                        var callback = (arguments.Length == 1 ? arguments[0] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();

                                var message = "V8 Script Engine : Started";
                                Log.Trace(message, configuration.Verbose);
                                runner.PostTask(new CallbackTask(context, callback, JsonMapper.ToJson(new StatusHelper("OK", message))));

                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            var message = "V8 Script Engine : Started";
                            Log.Trace(message, configuration.Verbose);
                            returnValue = CefV8Value.CreateString(JsonMapper.ToJson(new StatusHelper("OK", message)));
                        }
                    }
                    else
                    {
                        returnValue = DontMeetRequirements(context, null);
                    };
                }
                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }
        protected CefV8Value ToCefV8Value(IV8PluginRouter router, object result)
        {
            if (result == null)
            {
                return(CefV8Value.CreateNull());
            }

            // VALUES FROM REMOTE PLUGINS
            var remoteResult = result as ResultData;

            if (remoteResult != null)
            {
                switch (remoteResult.DataType)
                {
                case ResultDataType.Scalar:
                    if (remoteResult.Items != null && remoteResult.Items.Count != 0)
                    {
                        return(ToCefV8Value(router, remoteResult.Items[0]));
                    }
                    return(CefV8Value.CreateNull());

                case ResultDataType.Array:
                {
                    var cefArray = CefV8Value.CreateArray(remoteResult.Items.Count);
                    if (remoteResult.Items != null)
                    {
                        for (var resultIndex = 0; resultIndex < remoteResult.Items.Count; ++resultIndex)
                        {
                            var cefValue = ToCefV8Value(router, remoteResult.Items[resultIndex]);
                            cefArray.SetValue(resultIndex, cefValue);
                        }
                    }
                    return(cefArray);
                }

                case ResultDataType.Dictionary:
                {
                    var cefObject = CefV8Value.CreateObject(null);
                    if (remoteResult.Items != null)
                    {
                        foreach (var dictionaryItem in remoteResult.Items)
                        {
                            if (string.IsNullOrEmpty(dictionaryItem.Name))
                            {
                                continue;
                            }
                            var cefValue = ToCefV8Value(router, dictionaryItem);
                            cefObject.SetValue(dictionaryItem.Name, cefValue, CefV8PropertyAttribute.None);
                        }
                    }
                    return(cefObject);
                }
                }
            }
            var resultItem = result as ResultItem;

            if (resultItem != null)
            {
                return(ToCefV8Value(router, (object)resultItem.DynamicPlugin ?? resultItem.PlainData));
            }
            var pluginObjectDescriptor = result as PluginDescriptor;

            if (pluginObjectDescriptor != null)
            {
                return(V8PluginAdapter.CreateRemote(router, _plugin.PluginContext, pluginObjectDescriptor).V8Object);
            }

            // VALUES FROM REMOTE OR LOCAL PLUGINS
            var plainData = result as JToken;

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

            // VALUES FROM LOCAL PLUGINS
            var localArray = result as object[];

            if (localArray != null)
            {
                var cefArray = CefV8Value.CreateArray(localArray.Length);
                for (var resultIndex = 0; resultIndex < localArray.Length; ++resultIndex)
                {
                    var cefValue = ToCefV8Value(router, localArray[resultIndex]);
                    cefArray.SetValue(resultIndex, cefValue);
                }
                return(cefArray);
            }
            var localPlugin = result as JavaScriptPlugin;

            if (localPlugin != null)
            {
                return(V8PluginAdapter.CreateLocal(router, _plugin.PluginContext, localPlugin).V8Object);
            }
            if (JavaScriptPlugin.IsDynamicPlugin(result))
            {
                var dynPlugin = JavaScriptPlugin.CreateFromObject(PluginProcess.Renderer, result);
                _plugin.PluginContext.PluginManager.AddLocalPlugin(dynPlugin);
                return(V8PluginAdapter.CreateLocal(router, _plugin.PluginContext, dynPlugin).V8Object);
            }

            // local C# POCO
            return(CefNativeValueConverter.ToCef(result));
        }
Esempio n. 20
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var runner  = CefTaskRunner.GetForCurrentThread();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "create")
                {
                    var address = "";
                    var port    = 0;
                    var threads = 1;

                    if (arguments.Length >= 1)
                    {
                        address = arguments[0].GetStringValue();
                    }
                    if (arguments.Length >= 2)
                    {
                        port = arguments[1].GetIntValue();
                    }
                    if (arguments.Length >= 3)
                    {
                        threads = arguments[2].GetIntValue();
                    }

                    var handler = CefV8Value.CreateObject();
                    handler.SetValue("Address", CefV8Value.CreateString(address), CefV8PropertyAttribute.None);
                    handler.SetValue("Port", CefV8Value.CreateInt(port), CefV8PropertyAttribute.None);
                    handler.SetValue("Threads", CefV8Value.CreateInt(threads), CefV8PropertyAttribute.None);

                    handler.SetValue("onClientConnected", CefV8Value.CreateFunction("onClientConnected", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onClientDisconnected", CefV8Value.CreateFunction("onClientDisconnected", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onHttpRequest", CefV8Value.CreateFunction("onHttpRequest", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onServerCreated", CefV8Value.CreateFunction("onServerCreated", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onServerDestroyed", CefV8Value.CreateFunction("onServerDestroyed", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onWebSocketConnected", CefV8Value.CreateFunction("onWebSocketConnected", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onWebSocketMessage", CefV8Value.CreateFunction("onWebSocketMessage", this), CefV8PropertyAttribute.None);
                    handler.SetValue("onWebSocketRequest", CefV8Value.CreateFunction("onWebSocketRequest", this), CefV8PropertyAttribute.None);

                    handler.SetValue("sendHttp200Response", CefV8Value.CreateFunction("sendHttp200Response", this), CefV8PropertyAttribute.None);
                    handler.SetValue("sendHttp404Response", CefV8Value.CreateFunction("sendHttp404Response", this), CefV8PropertyAttribute.None);
                    handler.SetValue("sendHttp500Response", CefV8Value.CreateFunction("sendHttp500Response", this), CefV8PropertyAttribute.None);
                    handler.SetValue("sendHttpResponse", CefV8Value.CreateFunction("sendHttpResponse", this), CefV8PropertyAttribute.None);
                    handler.SetValue("sendRawData", CefV8Value.CreateFunction("sendRawData", this), CefV8PropertyAttribute.None);
                    handler.SetValue("sendWebSocketMessage", CefV8Value.CreateFunction("sendWebSocketMessage", this), CefV8PropertyAttribute.None);

                    handler.SetValue("connect", CefV8Value.CreateFunction("connect", this), CefV8PropertyAttribute.None);

                    if (this.parent != null && !this.parent.Servers.Any(s => s.Address == address && s.Port == port && s.Threads == threads))
                    {
                        this.parent.Servers.Add(new ServerHandler(address, port, threads));
                    }
                    returnValue = handler;
                }
                else if (name == "connect")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null)
                        {
                            serverHandler.Connect();
                            if (arguments.Length >= 1 && arguments[0].IsFunction)
                            {
                                new Task(() =>
                                {
                                    context.Enter();
                                    runner.PostTask(new CallbackTask(context, arguments[0]));
                                    context.Exit();
                                }).Start();
                            }
                        }
                    }
                }
                else if (name == "onClientConnected" ||
                         name == "onClientDisconnected" ||
                         name == "onHttpRequest" ||
                         name == "onServerCreated" ||
                         name == "onServerDestroyed" ||
                         name == "onWebSocketConnected" ||
                         name == "onWebSocketMessage" ||
                         name == "onWebSocketRequest")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 1 && arguments[0].IsFunction)
                        {
                            serverHandler.AddEventListener(name, new WebCallback(context, runner, arguments[0]));
                        }
                    }
                }
                else if (name == "sendHttp200Response")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 3)
                        {
                            var id          = arguments[0].GetIntValue();
                            var contentType = arguments[1].GetStringValue();
                            var data        = Encoding.UTF8.GetBytes(arguments[2].GetStringValue());
                            serverHandler.sendHttp200Response(id, contentType, data);
                        }
                    }
                }
                else if (name == "sendHttp404Response")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 1)
                        {
                            var id = arguments[0].GetIntValue();
                            serverHandler.sendHttp404Response(id);
                        }
                    }
                }
                else if (name == "sendHttp500Response")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 2)
                        {
                            var id    = arguments[0].GetIntValue();
                            var error = arguments[1].GetStringValue();
                            serverHandler.sendHttp500Response(id, error);
                        }
                    }
                }
                else if (name == "sendHttpResponse")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 5)
                        {
                            var id            = arguments[0].GetIntValue();
                            var responseCode  = arguments[1].GetIntValue();
                            var contentType   = arguments[2].GetStringValue();
                            var contentLength = arguments[3].GetIntValue();
                            var headers       = arguments[4].GetStringValue();
                            serverHandler.sendHttpResponse(id, responseCode, contentType, contentLength, headers);
                        }
                    }
                }
                else if (name == "sendRawData")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 2)
                        {
                            var id   = arguments[0].GetIntValue();
                            var data = Encoding.UTF8.GetBytes(arguments[1].GetStringValue());
                            serverHandler.sendRawData(id, data);
                        }
                    }
                }
                else if (name == "sendWebSocketMessage")
                {
                    var dic = GetSettings(obj, arguments);
                    if (this.parent != null && dic["Address"] != null && dic["Port"] != null && dic["Threads"] != null && !string.IsNullOrEmpty(dic["Address"].ToString()) && (int)dic["Port"] > 0 && (int)dic["Threads"] > 0)
                    {
                        var serverHandler = this.parent.Servers.SingleOrDefault(s => !string.IsNullOrEmpty(s.Address) && s.Address == dic["Address"].ToString() && s.Port == (int)dic["Port"] && s.Threads == (int)dic["Threads"]);
                        if (serverHandler != null && arguments.Length >= 2)
                        {
                            var id   = arguments[0].GetIntValue();
                            var data = Encoding.UTF8.GetBytes(arguments[1].GetStringValue());
                            serverHandler.sendWebSocketMessage(id, data);
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }
Esempio n. 21
0
 protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
 {
     returnValue = CefV8Value.CreateNull();
     exception   = null;
     return(true);
 }
Esempio n. 22
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            Browser father = null;

            LogManager.CefLog("-> Entering JS Execute. Func: " + name + " arg len: " + arguments.Length);

            father = CefUtil.GetBrowserFromCef(_browser);

            if (father == null)
            {
                LogManager.SimpleLog("cef", "NO FATHER FOUND FOR BROWSER " + _browser.Identifier);
                returnValue = CefV8Value.CreateNull();
                exception   = "NO FATHER WAS FOUND.";
                return(false);
            }
            if (!CefUtil.DISABLE_CEF)
            {
                LogManager.CefLog("-> Father was found!");
                try
                {
                    if (name == "resourceCall")
                    {
                        LogManager.CefLog("-> Entering resourceCall...");

                        List <object> args = new List <object>();

                        for (int i = 1; i < arguments.Length; i++)
                        {
                            args.Add(arguments[i].GetValue());
                        }

                        LogManager.CefLog("-> Executing callback...");

                        object output = father._callback.call(arguments[0].GetStringValue(), args.ToArray());

                        LogManager.CefLog("-> Callback executed!");

                        returnValue = V8Helper.CreateValue(output);
                        exception   = null;
                        return(true);
                    }

                    if (name == "resourceEval")
                    {
                        LogManager.CefLog("-> Entering resource eval");
                        object output = father._callback.eval(arguments[0].GetStringValue());
                        LogManager.CefLog("-> callback executed!");

                        returnValue = V8Helper.CreateValue(output);
                        exception   = null;
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    LogManager.CefLog(ex, "EXECUTE JS FUNCTION");
                }
            }
            returnValue = CefV8Value.CreateNull();
            exception   = "";
            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));
        }
Esempio n. 24
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);
        }
 private static ICefV8Value CreateNullValue()
 {
     return(new CefV8ValueImpl(CefV8Value.CreateNull()));
 }
Esempio n. 26
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name == "Create")
                {
                    var Handler = CefV8Value.CreateObject();
                    Handler.SetValue("open", CefV8Value.CreateFunction("open", this), CefV8PropertyAttribute.None);
                    Handler.SetValue("send", CefV8Value.CreateFunction("send", this), CefV8PropertyAttribute.None);
                    Handler.SetValue("onreadystatechange", CefV8Value.CreateFunction("onreadystatechange", this), CefV8PropertyAttribute.None);
                    Handler.SetValue("setRequestHeader", CefV8Value.CreateFunction("setRequestHeader", this), CefV8PropertyAttribute.None);
                    Handler.SetValue("getResponseHeader", CefV8Value.CreateFunction("getResponseHeader", this), CefV8PropertyAttribute.None);
                    returnValue = Handler;
                }
                else if (name == "open")
                {
                    if (arguments.Length >= 2)
                    {
                        var method = arguments[0].GetStringValue();
                        var url    = arguments[1].GetStringValue();

                        _req        = (HttpWebRequest)WebRequest.Create(arguments[1].GetStringValue());
                        _req.Method = method;
                    }
                }
                else if (name == "send")
                {
                    string data = null;

                    try
                    {
                        if (_req.Method == "POST" && arguments.Length == 1)
                        {
                            if (arguments[0].IsString)
                            {
                                var pd = Encoding.UTF8.GetBytes(arguments[0].GetStringValue());
                                _req.GetRequestStream().Write(pd, 0, pd.Length);
                            }
                            else if (arguments[0].IsArray)
                            {
                                var result = arguments[0];
                                var values = new List <char>();
                                for (int i = 0; i < result.GetArrayLength(); i++)
                                {
                                    var value = result.GetValue(i);
                                    values.Add(Extension.ConvertToV8Value(value));
                                }

                                var pd = values.Select(c => (byte)c).ToArray();
                                _req.GetRequestStream().Write(pd, 0, pd.Length);
                            }
                        }

                        _rsp = (HttpWebResponse)_req.GetResponse();
                        if (_rsp.StatusCode == HttpStatusCode.OK)
                        {
                            var d = new StreamReader(_rsp.GetResponseStream()).ReadToEnd();
                            if (!string.IsNullOrEmpty(d))
                            {
                                data = d;
                            }
                        }
                    }
                    catch {}

                    if (data != null)
                    {
                        returnValue = CefV8Value.CreateString(data);
                    }
                }
                else if (name == "setRequestHeader")
                {
                    if (arguments.Length == 2)
                    {
                        if (_req != null)
                        {
                            var _name = arguments[0].GetStringValue();
                            var val   = arguments[1].GetStringValue();

                            if (!string.IsNullOrEmpty(_name) && !string.IsNullOrEmpty(val))
                            {
                                if (_name.ToLower() == "user-agent")
                                {
                                    _req.UserAgent = val;
                                }
                                else if (_name.ToLower() == "connection")
                                {
                                    _req.KeepAlive = val.ToLower() == "keep-alive";
                                }
                                else
                                {
                                    _req.Headers.Add(_name, val);
                                }
                            }
                        }
                    }
                }
                else if (name == "getResponseHeader")
                {
                    string val = null;
                    if (arguments.Length == 1 && _rsp != null)
                    {
                        val = _rsp.Headers[arguments[0].GetStringValue()];
                    }

                    if (val != null)
                    {
                        returnValue = CefV8Value.CreateString(val);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }
Esempio n. 27
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                if (name.ToLower().Equals("back"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            back();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        back();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("copy"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            copy();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        copy();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("cut"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            cut();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        cut();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("delete"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            delete();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        delete();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("find"))
                {
                    if (arguments.Length >= 5)
                    {
                        var identifier = arguments[0].GetIntValue();
                        var searchText = arguments[1].GetStringValue();
                        var forward    = arguments[2].GetBoolValue();
                        var matchCase  = arguments[3].GetBoolValue();
                        var findNext   = arguments[4].GetBoolValue();
                        var callback   = (arguments.Length == 6 ? arguments[5] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                find(identifier, searchText, forward, matchCase, findNext);
                                runner.PostTask(new CallbackTask(context, callback, null));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            find(identifier, searchText, forward, matchCase, findNext);
                        }
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("forward"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            forward();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        forward();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("getsource"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            getSource();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        getSource();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("getzoomlevel"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            runner.PostTask(new CallbackTask(context, callback, getZoomLevel()));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        returnValue = CefV8Value.CreateDouble(getZoomLevel());
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("load"))
                {
                    if (arguments.Length >= 1)
                    {
                        var url      = arguments[0].GetStringValue();
                        var callback = (arguments.Length == 2 ? arguments[1] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                load(url);
                                runner.PostTask(new CallbackTask(context, callback, null));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            load(url);
                        }
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("loadstring"))
                {
                    if (arguments.Length >= 2)
                    {
                        var html     = arguments[0].GetStringValue();
                        var url      = arguments[1].GetStringValue();
                        var callback = (arguments.Length == 3 ? arguments[2] : null);

                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                loadString(html, url);
                                runner.PostTask(new CallbackTask(context, callback, null));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            loadString(html, url);
                        }
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("paste"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            paste();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        paste();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("print"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            print();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        print();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("redo"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            redo();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        redo();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("refresh"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            refresh();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        refresh();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("selectall"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            selectAll();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        selectAll();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("showdevtools"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            showDevTools();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        showDevTools();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("stop"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            stop();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        stop();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("undo"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            undo();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        undo();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("viewsource"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            viewSource();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        viewSource();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("shutdown"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            shutdown();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        shutdown();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("printtopdf"))
                {
                    if (arguments.Length >= 1)
                    {
                        var path      = arguments[0].GetStringValue();
                        var settings  = new CefPdfPrintSettings();
                        var _callback = new CefPdfClient();

                        var callback = (arguments.Length == 2 ? arguments[1] : null);
                        if (callback != null && callback.IsFunction)
                        {
                            var runner = CefTaskRunner.GetForCurrentThread();
                            new Task(() =>
                            {
                                context.Enter();
                                printToPDF(path, settings, null);
                                runner.PostTask(new CallbackTask(context, callback, _callback));
                                context.Exit();
                            }).Start();
                        }
                        else
                        {
                            printToPDF(path, settings, _callback);
                        }
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("getwindowsize"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            getWindowSize();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        getWindowSize();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("update"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            Update();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        Update();
                    }
                    return(true);
                }
                else if (name.ToLower().Equals("checkforupdates"))
                {
                    var callback = (arguments.Length == 1 ? arguments[0] : null);
                    if (callback != null && callback.IsFunction)
                    {
                        var runner = CefTaskRunner.GetForCurrentThread();
                        new Task(() =>
                        {
                            context.Enter();
                            CheckForUpdates();
                            runner.PostTask(new CallbackTask(context, callback, null));
                            context.Exit();
                        }).Start();
                    }
                    else
                    {
                        CheckForUpdates();
                    }
                    return(true);
                }
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }

            return(false);
        }
Esempio n. 28
0
        public object Deserialize(CefValue value, Type targetType, ObjectSerializer objectSerializer)
        {
            if (!CanHandle(value, targetType))
            {
                throw new InvalidOperationException();
            }

            var valueType = value.GetValueType();

            if (valueType == CefValueType.String)
            {
                return(CefV8Value.CreateString(value.GetString()));
            }

            if (valueType == CefValueType.Int)
            {
                return(CefV8Value.CreateInt(value.GetInt()));
            }

            if (valueType == CefValueType.Double)
            {
                return(CefV8Value.CreateDouble(value.GetDouble()));
            }

            if (value.IsType(CefTypes.Int64))
            {
                return(CefV8Value.CreateDouble(value.GetInt64()));
            }

            if (value.IsType(CefTypes.Time))
            {
                return(CefV8Value.CreateDate(value.GetTime()));
            }

            if (valueType == CefValueType.Bool)
            {
                return(CefV8Value.CreateBool(value.GetBool()));
            }

            if (valueType == CefValueType.List)
            {
                using (var list = value.GetList())
                {
                    if (list.Count > 0)
                    {
                        var array = CefV8Value.CreateArray(list.Count);
                        for (var i = 0; i < list.Count; i++)
                        {
                            using (var cefValue = list.GetValue(i))
                            {
                                array.SetValue(i,
                                               (CefV8Value)objectSerializer.Deserialize(cefValue, typeof(CefV8Value)));
                            }
                        }

                        return(array);
                    }
                }
            }

            if (valueType == CefValueType.Dictionary)
            {
                using (var dictionary = value.GetDictionary())
                    using (var valDict = dictionary.GetDictionary(ObjectSerializer.ValuePropertyName))
                    {
                        var typeId = dictionary.GetString(ObjectSerializer.TypeIdPropertyName);
                        if (typeId == ObjectSerializer.DictionaryTypeId)
                        {
                            var obj = CefV8Value.CreateObject();
                            foreach (var key in valDict.GetKeys())
                            {
                                obj.SetValue(key, (CefV8Value)objectSerializer.Deserialize(valDict.GetValue(key), typeof(CefV8Value)));
                            }
                            return(obj);
                        }
                        else
                        {
                            var deserialized = objectSerializer.Deserialize(value, typeof(object));
                            if (deserialized is ObjectDescriptor descriptor)
                            {
                                return(new ObjectBinder(descriptor, objectSerializer, functionCallPromiseRegistry).BindToNew());
                            }
                        }
                    }
            }

            return(CefV8Value.CreateNull());
        }
Esempio n. 29
0
 public IJavascriptObject CreateNull()
 {
     return(new CefV8_JavascriptObject(CefV8Value.CreateNull()));
 }
Esempio n. 30
0
        protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception)
        {
            returnValue = CefV8Value.CreateNull();
            exception   = null;

            try
            {
                var context = CefV8Context.GetCurrentContext();
                var browser = context.GetBrowser();
                var frame   = browser.GetMainFrame();

                var className  = name.Substring(0, name.LastIndexOf('.'));
                var methodName = name.Substring(name.LastIndexOf('.') + 1);

                if (!string.IsNullOrEmpty(className) && !string.IsNullOrEmpty(methodName))
                {
                    var type = GetClassType(className);
                    if (type != null)
                    {
                        var ret = false;
                        foreach (var method in type.GetMethods())
                        {
                            if (method.Name == methodName && validTypes.Contains(method.ReturnType))
                            {
                                var parameters = method.GetParameters();
                                var pc         = parameters.Where(ss => validTypes.Contains(ss.ParameterType)).Count();
                                if (parameters.Length == pc && arguments.Length >= parameters.Length)
                                {
                                    var        args     = new List <object>();
                                    CefV8Value callback = null;
                                    if (parameters.Length + 1 == arguments.Length)
                                    {
                                        callback = arguments[arguments.Length - 1];
                                    }

                                    for (int x = 0; x < parameters.Length; x++)
                                    {
                                        var a = Extension.ConvertToValue(arguments[x]);
                                        var p = parameters[x];
                                        if (a == null || (a != null && a.GetType() == p.ParameterType))
                                        {
                                            args.Add(a);
                                        }
                                    }

                                    if (method.ReturnType != typeof(void))
                                    {
                                        if (callback != null && callback.IsFunction)
                                        {
                                            ret = true;
                                            var runner = CefTaskRunner.GetForCurrentThread();
                                            new Task(() =>
                                            {
                                                context.Enter();
                                                var value = method.Invoke(this, args.ToArray());
                                                if (runner != null)
                                                {
                                                    runner.PostTask(new CallbackTask(context, callback, value));
                                                }
                                                context.Exit();
                                            }).Start();
                                        }
                                        else
                                        {
                                            returnValue = InvokeMethod(method, args, method.ReturnType);
                                            if (returnValue != null)
                                            {
                                                ret = true;
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                        return(ret);
                    }
                    else
                    {
                        type = GetClassType(name);
                        if (type != null)
                        {
                            var args     = new List <object>();
                            var argTypes = new List <Type>();
                            for (int x = 0; x < arguments.Length; x++)
                            {
                                var result = arguments[x];
                                if (result.IsBool)
                                {
                                    args.Add(result.GetBoolValue());
                                    argTypes.Add(typeof(bool));
                                }
                                else if (result.IsDate)
                                {
                                    args.Add(result.GetDateValue());
                                    argTypes.Add(typeof(DateTime));
                                }
                                else if (result.IsInt)
                                {
                                    args.Add(result.GetIntValue());
                                    argTypes.Add(typeof(int));
                                }
                                else if (result.IsDouble)
                                {
                                    args.Add(result.GetDoubleValue());
                                    argTypes.Add(typeof(double));
                                }
                                else if (result.IsNull || result.IsUndefined)
                                {
                                    args.Add(null);
                                    argTypes.Add(null);
                                }
                                else if (result.IsString)
                                {
                                    args.Add(result.GetStringValue());
                                    argTypes.Add(typeof(string));
                                }
                                else if (result.IsUInt)
                                {
                                    args.Add(result.GetUIntValue());
                                    argTypes.Add(typeof(uint));
                                }
                                else if (result.IsArray)
                                {
                                    var values = new List <dynamic>();
                                    for (int i = 0; i < result.GetArrayLength(); i++)
                                    {
                                        var value = result.GetValue(i);
                                        values.Add(Extension.ConvertToV8Value(value));
                                    }
                                    args.Add(values);
                                    argTypes.Add(typeof(Array));
                                }
                            }

                            ConstructorInfo constructor = null;
                            foreach (var constr in type.GetConstructors())
                            {
                                var parameters = constr.GetParameters().Where(ss => validTypes.Contains(ss.ParameterType)).ToList();
                                if (parameters.Count == argTypes.Count)
                                {
                                    constructor = type.GetConstructor(argTypes.ToArray());
                                    if (constructor == null)
                                    {
                                        for (int x = 0; x < parameters.Count; x++)
                                        {
                                            var a = argTypes[x];
                                            var p = parameters[x];
                                            var v = args[x];

                                            if (p.ParameterType != a)
                                            {
                                                argTypes[x] = p.ParameterType;
                                                if (v != null)
                                                {
                                                    if (p.ParameterType == typeof(char[]) && a == typeof(string))
                                                    {
                                                        args[x] = ((string)v).ToCharArray();
                                                    }
                                                    else
                                                    {
                                                        args[x] = Convert.ChangeType(v, p.ParameterType);
                                                    }
                                                }
                                            }
                                        }
                                        constructor = type.GetConstructor(argTypes.ToArray());
                                        if (constructor != null)
                                        {
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }

                            returnValue = InvokeContructor(constructor, args, type);
                            if (returnValue != null)
                            {
                                return(true);
                            }
                        }
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                returnValue = CefV8Value.CreateNull();
                exception   = ex.Message;
                return(true);
            }
        }