public CefV8Value CreateObject() { V8Value = CefV8Value.CreateObject(); V8Value.SetValue("log", CefV8Value.CreateFunction("log", V8Handler), CefV8PropertyAttribute.None); return(V8Value); }
// TODO: CreateV8Handler self/universal // TODO: CreateV8Accessor self/universal public CefV8Value CreateScriptableObject(object instance) { // TODO: if object doesn't have properties -> do not create accessor var v8Handler = new ScriptableObjectV8Handler(this, instance); var v8Accessor = new ScriptableObjectV8Accessor(this, instance); var obj = CefV8Value.CreateObject(v8Accessor); foreach (var property in this.PropertyDispatchTable.GetValues()) { obj.SetValue(property.Name, (property.CanRead ? CefV8AccessControl.AllCanRead : 0) | (property.CanWrite ? CefV8AccessControl.AllCanWrite : 0), CefV8PropertyAttribute.DontDelete); } foreach (var method in this.DispatchTable.GetValues()) { if (method.Hidden) { continue; } obj.SetValue(method.Name, CefV8Value.CreateFunction(method.Name, v8Handler) ); } return(obj); }
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); }
/// <summary> /// Register custom variables and functions as the object 'reko' in the global context /// </summary> public void RegisterGlobals() { context.Acquire(() => { var global = context.GetGlobal(); var rekoObj = CefV8Value.CreateObject(); var dumpBytesFn = new Proto_DumpBytes(decompiler); var procListRenderer = new ProcedureListRenderer(decompiler); global.SetValue("reko", rekoObj); RegisterAsyncFunction(rekoObj, "OpenFile", new OpenFileHandler(promiseFactory, pendingPromises)); RegisterAsyncFunction(rekoObj, "Proto_DisassembleRandomBytes", new Func <string, string, string>(Proto_DisassembleRandomBytes.Execute)); RegisterAsyncFunction(rekoObj, "Proto_GeneratePng", new Func <int, byte[]>(Proto_GeneratePng.Execute)); RegisterAsyncFunction(rekoObj, "LoadFile", new Func <string, string?, Address?, bool>(decompiler.Load)); RegisterAsyncFunction(rekoObj, "Scan", new Action(decompiler.ScanPrograms)); RegisterAsyncFunction(rekoObj, "DumpBytes", new Func <string, string, long, string>(dumpBytesFn.Execute)); RegisterAsyncFunction(rekoObj, "GetProcedureList", new Func <string, string>(procListRenderer.Render)); RegisterFunction(rekoObj, "TestListener", new Action(() => { var listener = services.RequireService <DecompilerEventListener>(); listener.Info(new NullCodeLocation("web"), "Hello World"); })); RegisterFunction(rekoObj, "RegisterEventListener", new Proto_RegisterEventListener(eventListeners)); RegisterFunction(rekoObj, "RenderProjectView", new Func <string>(() => ProjectViewRenderer.RenderToHtml(decompiler))); RegisterFunction(rekoObj, "RenderProcedure", new Func <CefV8Value, CefV8Value>((CefV8Value key) => { var iKey = key.GetIntValue(); var proc = new ProcedureViewModel(iKey); var obj = CefV8Value.CreateObject(); obj.SetValue("name", CefV8Value.CreateString(proc.Name)); obj.SetValue("body", CefV8Value.CreateString(proc.Body)); return(obj); })); }); }
public CefV8Value CreateObject() { Handler = CefV8Value.CreateObject(); Handler.SetValue("setTimeout", CefV8Value.CreateFunction("setTimeout", this), CefV8PropertyAttribute.None); Handler.SetValue("setInterval", CefV8Value.CreateFunction("setInterval", this), CefV8PropertyAttribute.None); Handler.SetValue("back", CefV8Value.CreateFunction("back", this), CefV8PropertyAttribute.None); Handler.SetValue("copy", CefV8Value.CreateFunction("copy", this), CefV8PropertyAttribute.None); Handler.SetValue("cut", CefV8Value.CreateFunction("cut", this), CefV8PropertyAttribute.None); Handler.SetValue("delete", CefV8Value.CreateFunction("delete", this), CefV8PropertyAttribute.None); Handler.SetValue("find", CefV8Value.CreateFunction("find", this), CefV8PropertyAttribute.None); Handler.SetValue("forward", CefV8Value.CreateFunction("forward", this), CefV8PropertyAttribute.None); Handler.SetValue("getSource", CefV8Value.CreateFunction("getSource", this), CefV8PropertyAttribute.None); Handler.SetValue("getZoomLevel", CefV8Value.CreateFunction("getZoomLevel", this), CefV8PropertyAttribute.None); Handler.SetValue("load", CefV8Value.CreateFunction("load", this), CefV8PropertyAttribute.None); Handler.SetValue("loadString", CefV8Value.CreateFunction("loadString", this), CefV8PropertyAttribute.None); Handler.SetValue("paste", CefV8Value.CreateFunction("paste", this), CefV8PropertyAttribute.None); Handler.SetValue("print", CefV8Value.CreateFunction("print", this), CefV8PropertyAttribute.None); Handler.SetValue("redo", CefV8Value.CreateFunction("redo", this), CefV8PropertyAttribute.None); Handler.SetValue("refresh", CefV8Value.CreateFunction("refresh", this), CefV8PropertyAttribute.None); Handler.SetValue("selectAll", CefV8Value.CreateFunction("selectAll", this), CefV8PropertyAttribute.None); Handler.SetValue("showDevTools", CefV8Value.CreateFunction("showDevTools", this), CefV8PropertyAttribute.None); Handler.SetValue("stop", CefV8Value.CreateFunction("stop", this), CefV8PropertyAttribute.None); Handler.SetValue("undo", CefV8Value.CreateFunction("undo", this), CefV8PropertyAttribute.None); Handler.SetValue("viewSource", CefV8Value.CreateFunction("viewSource", this), CefV8PropertyAttribute.None); Handler.SetValue("shutdown", CefV8Value.CreateFunction("shutdown", this), CefV8PropertyAttribute.None); Handler.SetValue("printToPDF", CefV8Value.CreateFunction("printToPDF", this), CefV8PropertyAttribute.None); Handler.SetValue("getWindowSize", CefV8Value.CreateFunction("getwindowsize", this), CefV8PropertyAttribute.None); Handler.SetValue("update", CefV8Value.CreateFunction("update", this), CefV8PropertyAttribute.None); Handler.SetValue("checkForUpdates", CefV8Value.CreateFunction("checkforupdates", this), CefV8PropertyAttribute.None); return(Handler); }
public CefV8Value CreateObject() { CefV8Value Handler = CefV8Value.CreateObject(); Handler.SetValue("Protocols", CefV8Value.CreateFunction("Protocols", this), CefV8PropertyAttribute.None); return(Handler); }
public CefV8Value CreateObject() { Handler = CefV8Value.CreateObject(); Handler.SetValue("query", CefV8Value.CreateFunction("query", this), CefV8PropertyAttribute.None); Handler.SetValue("reader", CefV8Value.CreateFunction("reader", this), CefV8PropertyAttribute.None); return(Handler); }
protected override bool OnProcessMessageReceived(CefBrowser browser, CefProcessId sourceProcess, CefProcessMessage message) { if (message.Name == "SetOverlayAPI") { // 対象のフレームを取得 var frameName = message.Arguments.GetString(0); var frame = GetFrameByName(browser, frameName); var overlayName = message.Arguments.GetString(1); var overlayVersion = message.Arguments.GetString(2); // API を設定 if (frame != null && frame.V8Context.Enter()) { var apiObject = CefV8Value.CreateObject(null); var broadcastMessageFunction = CefV8Value.CreateFunction( BuiltinFunctionHandler.BroadcastMessageFunctionName, builtinFunctionHandler); var sendMessageFunction = CefV8Value.CreateFunction( BuiltinFunctionHandler.SendMessageFunctionName, builtinFunctionHandler); var overlayMessageFunction = CefV8Value.CreateFunction( BuiltinFunctionHandler.OverlayMessageFunctionName, builtinFunctionHandler); var endEncounterFunction = CefV8Value.CreateFunction( BuiltinFunctionHandler.EndEncounterFunctionName, builtinFunctionHandler); apiObject.SetValue("version", CefV8Value.CreateString(overlayVersion), CefV8PropertyAttribute.ReadOnly); apiObject.SetValue("overlayName", CefV8Value.CreateString(overlayName), CefV8PropertyAttribute.ReadOnly); apiObject.SetValue( BuiltinFunctionHandler.BroadcastMessageFunctionName, broadcastMessageFunction, CefV8PropertyAttribute.ReadOnly); apiObject.SetValue( BuiltinFunctionHandler.SendMessageFunctionName, sendMessageFunction, CefV8PropertyAttribute.ReadOnly); apiObject.SetValue( BuiltinFunctionHandler.OverlayMessageFunctionName, overlayMessageFunction, CefV8PropertyAttribute.ReadOnly); apiObject.SetValue( BuiltinFunctionHandler.EndEncounterFunctionName, endEncounterFunction, CefV8PropertyAttribute.ReadOnly); frame.V8Context.GetGlobal().SetValue("OverlayPluginApi", apiObject, CefV8PropertyAttribute.ReadOnly); frame.V8Context.Exit(); } return(true); } return(base.OnProcessMessageReceived(browser, sourceProcess, message)); }
public void BindObjects(CefV8Value target) { foreach (var def in this.objects.Values.Where(_ => !_.Extension)) { var binder = ScriptableObjectBinder.Get(def.TargetType, def.Options); List <CefV8Value> proxies = null; var name = def.MemberName; var obj = target; if (name.Contains('.')) { proxies = new List <CefV8Value>(); var parts = name.Split('.'); for (var i = 0; i < parts.Length - 1; i++) { name = parts[i]; var nsObj = obj.GetValue(name); proxies.Add(nsObj); if (nsObj.IsUndefined) { var newObj = CefV8Value.CreateObject(); proxies.Add(newObj); obj.SetValue(name, newObj); obj = newObj; continue; } else if (nsObj.IsObject) { obj = nsObj; continue; } else { throw new JSBindingException("Invalid member access expression. Invalid object in path."); } } name = parts[parts.Length - 1]; } var boundObject = binder.CreateScriptableObject(def.Target); obj.SetValue(name, boundObject); boundObject.Dispose(); if (proxies != null) { foreach (var proxy in proxies) { proxy.Dispose(); } } } }
public void Test_GetSimpleValue_Object() { Test(() => { object res = null; bool ok = _CefV8_Converter.GetSimpleValue(CefV8Value.CreateObject(null).Convert(), out res); ok.Should().BeFalse(); res.Should().BeNull(); }); }
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { var global = context.GetGlobal(); var extent = CefV8Value.CreateObject(null); global.SetValue("V8", extent, CefV8PropertyAttribute.None); base.OnContextCreated(browser, frame, context); }
public CefV8Value ToCef(object nativeObject) { var cefObject = CefV8Value.CreateObject(null); foreach (var member in _members.Values) { member.SetCefValue(cefObject, nativeObject); } return(cefObject); }
private void InitializeContext(CefBrowser browser, CefFrame frame, CefV8Context context) { if (_pluginContext == null) { Logger.Error("Could not locate plugin context for V8. Browser {0} Frame {1}", browser.Identifier, frame.Identifier); return; } // TODO : Put in an optimization to not create the JS Object model if the current browser is a DEV TOOLS instance var window = context.GetGlobal(); foreach (var pluginId in _pluginContext.GetPluginIds()) { var pluginPath = pluginId.Split('.'); var pluginV8HostObject = window; var clashDetected = false; for (var pluginPathSectionIndex = 0; pluginPathSectionIndex < pluginPath.Length; pluginPathSectionIndex++) { var pathSection = pluginPath[pluginPathSectionIndex]; if (pluginPathSectionIndex == 0 && pathSection == "window") { // Fully scoped path - parent should stay as the root/global object until next section continue; } if (pluginV8HostObject.HasValue(pathSection)) { pluginV8HostObject = pluginV8HostObject.GetValue(pathSection); if (!pluginV8HostObject.IsObject) { // Most likely a clash of JS paths between plugins // TODO: warn that this current plugin could not be added clashDetected = true; break; } } else { var child = CefV8Value.CreateObject(null); pluginV8HostObject.SetValue(pathSection, child, CefV8PropertyAttribute.DontEnum | CefV8PropertyAttribute.DontDelete); pluginV8HostObject = child; } } if (clashDetected) { continue; } V8PluginAdapter.Create(_pluginContext.GetPluginById(pluginId), pluginV8HostObject); } }
/// <summary> /// 执行JS方法 /// </summary> /// <param name="name">方法名</param> /// <param name="obj"></param> /// <param name="arguments"></param> /// <param name="returnValue"></param> /// <param name="exception"></param> /// <returns></returns> protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) { exception = null; try { List <object> paras = V8ValueClrMap.ConvertToClrParameters(arguments); var clrObj = V8ValueClrMap.GetClrValue(obj); Type t = null; if (obj.IsObject) { t = clrObj.GetType(); } var function = t.GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly); if (function != null) { var objRst = function.Invoke(clrObj, paras.Count == 0 ? null : paras.ToArray()); if (objRst is CefV8Handler) { returnValue = CefV8Value.CreateObject(null); Bind(name, objRst as CefV8Handler, returnValue); } else { returnValue = V8ValueClrMap.ConvertToV8Value(objRst); } } else { exception = "方法没有找到:" + name; returnValue = CefV8Value.CreateString(""); var message3 = CefProcessMessage.Create("Exception"); message3.Arguments.SetString(0, exception); //var success2 = Browser.SendProcessMessage(CefProcessId.Browser, message3); return(true); } return(true); } catch (Exception ee) { returnValue = CefV8Value.CreateString(""); exception = ee.Message; returnValue = CefV8Value.CreateString(""); var message3 = CefProcessMessage.Create("Exception"); message3.Arguments.SetString(0, ee.ToString()); //var success2 = Browser.SendProcessMessage(CefProcessId.Browser, message3); return(true); } }
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); }
public CefV8Value CreateObject() { Handler = CefV8Value.CreateObject(); Handler.SetValue("compile", CefV8Value.CreateFunction("compile", this), CefV8PropertyAttribute.None); Handler.SetValue("consoleExecute", CefV8Value.CreateFunction("consoleExecute", this), CefV8PropertyAttribute.None); Handler.SetValue("execute", CefV8Value.CreateFunction("execute", this), CefV8PropertyAttribute.None); Handler.SetValue("loadScript", CefV8Value.CreateFunction("loadScript", this), CefV8PropertyAttribute.None); Handler.SetValue("loadScriptCompiled", CefV8Value.CreateFunction("loadScriptCompiled", this), CefV8PropertyAttribute.None); Handler.SetValue("terminateExecution", CefV8Value.CreateFunction("terminateExecution", this), CefV8PropertyAttribute.None); Handler.SetValue("verboseConsoleExecute", CefV8Value.CreateFunction("verboseConsoleExecute", this), CefV8PropertyAttribute.None); Handler.SetValue("runStartupFile", CefV8Value.CreateFunction("runStartupFile", this), CefV8PropertyAttribute.None); return(Handler); }
private void CefWebBrowserMainView_CreateJSObject(object sender, Xilium.CefGlue.WindowsForms.CefWebBrowser.CefWebCreateJSObjectEventArgs e) { // Retrieve the context's window object. CefV8Value window = e.Context.GetGlobal(); // window.pos CefV8Value pos = CefV8Value.CreateObject(null); window.SetValue("pos", pos, CefV8PropertyAttribute.DontDelete | CefV8PropertyAttribute.ReadOnly); // window.pos.Message CefV8Value pos_Message = CefV8Value.CreateString("Hello Vue.js 讀書會"); pos.SetValue("Message", pos_Message, CefV8PropertyAttribute.DontDelete | CefV8PropertyAttribute.ReadOnly); }
public CefV8Value BindToNew() { var obj = CefV8Value.CreateObject(); functions?.Values.ToList().ForEach(m => m.Bind(obj)); propertyDescriptors?.ForEach(c => { var value = (CefV8Value)v8Serializer.Deserialize(c.ListValue, typeof(CefV8Value)); obj.SetValue(c.Name, value, CefV8PropertyAttribute.ReadOnly); c.ListValue.Dispose(); }); propertyDescriptors?.Clear(); return(obj); }
/// <summary> /// Create a new V8 plugin adapter. /// </summary> /// <param name="pluginObject"> /// The local or remote native plugin to adapt to V8. /// </param> /// <param name="v8HostObject"> /// Optional - if supplied, the adapter will add the native methods and events to this /// existing object instead of creating a new one with a property accessor. /// </param> private V8PluginAdapter(IV8Plugin pluginObject, CefV8Value v8HostObject = null) { Plugin = pluginObject; V8Object = v8HostObject; if (V8Object == null) { V8Object = CefV8Value.CreateObject(new PluginV8Accessor()); V8Object.SetUserData(this); } // Create a single method handler configured to handle all methods on the plugin var methodHandler = new PluginMethodV8Handler(Plugin); foreach (var methodDescriptor in Plugin.Descriptor.Methods) { V8Object.SetValue(methodDescriptor.MethodName, CefV8Value.CreateFunction(methodDescriptor.MethodName, methodHandler), CefV8PropertyAttribute.None); } foreach (var eventName in Plugin.Descriptor.Events) { // For each event, create a child object exposed as a property named after the event // The child object is a syntactic placeholder for the addListener/removeListener/hasListener/hasListeners methods var eventObject = CefV8Value.CreateObject(null); var eventHandler = new PluginEventV8Handler(Plugin, eventName); eventObject.SetValue(PluginEventV8Handler.MethodNameAddListener, CefV8Value.CreateFunction(PluginEventV8Handler.MethodNameAddListener, eventHandler), CefV8PropertyAttribute.None); eventObject.SetValue(PluginEventV8Handler.MethodNameRemoveListener, CefV8Value.CreateFunction(PluginEventV8Handler.MethodNameRemoveListener, eventHandler), CefV8PropertyAttribute.None); eventObject.SetValue(PluginEventV8Handler.MethodNameHasListener, CefV8Value.CreateFunction(PluginEventV8Handler.MethodNameHasListener, eventHandler), CefV8PropertyAttribute.None); eventObject.SetValue(PluginEventV8Handler.MethodNameHasListeners, CefV8Value.CreateFunction(PluginEventV8Handler.MethodNameHasListeners, eventHandler), CefV8PropertyAttribute.None); V8Object.SetValue(eventName, eventObject, CefV8PropertyAttribute.None); } }
/// <summary> /// 绑定数据并注册对象 /// 说明:已经过滤特殊名称,即不含系统自动生成的属性、方法 /// </summary> /// <param name="name">对象名称</param> /// <param name="obj">需要绑定的对象</param> /// <param name="window">用于注册的V8 JS引擎对象,类似于整个程序的窗口句柄</param> public static void Bind(string name, object obj, CefV8Value window) { var unmanagedWrapper = new UnmanagedWrapper(obj); var propertyAccessor = new PropertyAccessor(); //javascript对象包 CefV8Value javascriptWrapper = CefV8Value.CreateObject(propertyAccessor); //将非托管对象放到javascript对象包 javascriptWrapper.SetUserData(unmanagedWrapper); var handler = new BindingHandler(); unmanagedWrapper.Properties = GetProperties(obj.GetType()); CreateJavascriptProperties(javascriptWrapper, unmanagedWrapper.Properties); IList <string> methodNames = GetMethodNames(obj.GetType(), unmanagedWrapper.Properties); CreateJavascriptMethods(handler, javascriptWrapper, methodNames); window.SetValue(name, javascriptWrapper, CefV8PropertyAttribute.None); }
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); } }
private static ICefV8Value CreateObjectValue() { return(new CefV8ValueImpl(CefV8Value.CreateObject())); }
/// <summary> /// The on context created. /// </summary> /// <param name="browser"> /// The browser. /// </param> /// <param name="frame"> /// The frame. /// </param> /// <param name="context"> /// The context. /// </param> protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { #region Initialize var global = context.GetGlobal(); #endregion #region Exposed CefV8Value exposed = CefV8Value.CreateObject(); global.SetValue("exposed", exposed, CefV8PropertyAttribute.None); #endregion #region Cef Assembly var extension = new CefAssembly(browser, frame, context); extension.CreateObject(global, new List <string>() { "mscorlib", "System", "System.Core" }); //extension.CreateObject(global, AppDomain.CurrentDomain.GetAssemblies().Where(s => //{ // if (s.GetName().Name.StartsWith("blis")) return true; // return false; //}) //.Select(s => s.GetName().Name).ToList()); #endregion #region Custom XHR var xhr = new xhrObject(browser, frame, context); global.SetValue("xHttpRequest", xhr.CreateObject(), CefV8PropertyAttribute.None); #endregion #region V8 Engine API var v8Engine = new V8EngineObject(browser, frame, context); global.SetValue("V8Engine", v8Engine.CreateObject(), CefV8PropertyAttribute.None); #endregion #region Database API var database = new DatabaseObject(browser, frame, context); global.SetValue("DB", database.CreateObject(), CefV8PropertyAttribute.None); #endregion #region Console API var console = new ConsoleObject(browser, frame, context); global.SetValue("Console", database.CreateObject(), CefV8PropertyAttribute.None); #endregion #region Window API var window = new WindowObject(browser, frame, context); global.SetValue("Window", window.CreateObject(), CefV8PropertyAttribute.None); #endregion #region Server API var server = new ServerObject(browser, frame, context, this); global.SetValue("Server", server.CreateObject(), CefV8PropertyAttribute.None); #endregion #region ChromeDevToosProtocol Object var chromeDevToolsProtocol = new ChromeDevToolsProtocol(browser, frame, context); global.SetValue("DevTools", chromeDevToolsProtocol.CreateObject(), CefV8PropertyAttribute.None); #endregion #region OnContextCreated MessageRouter.OnContextCreated(browser, frame, context); context.Dispose(); #endregion }
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()); }
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); } }
public IJavascriptObject CreateObject(bool readOnly) { return(UpdateObject(CefV8Value.CreateObject(null), readOnly)); }
protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) { if (name == _name) { var bid = _context.GetBrowser()?.Identifier ?? 0; var fid = _context.GetFrame()?.Identifier ?? 0; var request = MessageBridgeRequest.Create(JavaScriptCommunicationBridge.EXECUTE_JAVASCRIPT_FUNCTION, bid, fid, _context.GetHashCode()); request.Arguments.Add(MessageValue.CreateString(_parentKey)); request.Arguments.Add(MessageValue.CreateString(_name)); var args = JavaScriptValue.CreateArray(); var index = 0; foreach (var arg in arguments) { var value = arg.ToJSValue(); if (value != null) { args.SetValue(index++, value); } } request.Arguments.Add(MessageValue.CreateString(args.ToDefinition())); var guid = Guid.NewGuid(); request.Arguments.Add(MessageValue.CreateString($"{guid}")); var response = _bridge.SendExecutionRequest(request); if (response.IsSuccess) { if (_functionInfo.IsAsync) { var callback = CefV8Value.CreateObject(); var successFunc = CefV8Value.CreateFunction("success", new JavaScriptBridgeFunctionCallbackHandler(/*_parentKey, _name,*/ guid, _context)); var errorFunc = CefV8Value.CreateFunction("error", new JavaScriptBridgeFunctionCallbackHandler(/*_parentKey, _name,*/ guid, _context)); callback.SetValue("success", successFunc); callback.SetValue("error", errorFunc); returnValue = callback; exception = null; } else { var retval = JavaScriptValue.FromJson(response.Arguments[0].GetString())?.ToCefV8Value(); exception = null; if (retval != null) { returnValue = retval; } else { returnValue = CefV8Value.CreateUndefined(); } } } else { exception = response.ExceptionMessage; returnValue = null; } return(true); } returnValue = null; exception = $"{name} is not defined."; return(true); }
public IJavascriptObject CreateObject() { return(UpdateObject(CefV8Value.CreateObject(null))); }
public IJavascriptObject CreateObject(ObjectObservability objectObservability) { return(UpdateObject(CefV8Value.CreateObject(null), objectObservability)); }
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)); }