public CefV8Value CreateObject() { CefV8Value Handler = CefV8Value.CreateObject(); Handler.SetValue("Protocols", CefV8Value.CreateFunction("Protocols", this), CefV8PropertyAttribute.None); return(Handler); }
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { if (frame.IsMain) { LogManager.CefLog("-> Setting main context!"); Browser father = CefUtil.GetBrowserFromCef(browser); if (father != null) { if (!CefUtil.DISABLE_CEF) { father._mainContext = context; } LogManager.CefLog("-> Main context set!"); } } CefV8Value global = context.GetGlobal(); CefV8Value func = CefV8Value.CreateFunction("resourceCall", new V8Bridge(browser)); global.SetValue("resourceCall", func, CefV8PropertyAttribute.None); CefV8Value func2 = CefV8Value.CreateFunction("resourceEval", new V8Bridge(browser)); global.SetValue("resourceEval", func2, CefV8PropertyAttribute.None); base.OnContextCreated(browser, frame, context); }
/// <summary> /// Call from CefRenderProcessHandler::OnContextCreated. Registers the /// JavaScripts functions with the new context. /// </summary> public void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { Helpers.RequireRendererThread(); // Do not keep any references to CefV8Value objects, otherwise // we should release all of them in OnContextReleased method (so we // can't rely on GC for this purpose). // Register function handlers with the 'window' object. using (var window = context.GetGlobal()) { var handler = new V8HandlerImpl(this, _config); CefV8PropertyAttribute attributes = CefV8PropertyAttribute.ReadOnly | CefV8PropertyAttribute.DontEnum | CefV8PropertyAttribute.DontDelete; // Add the query function. using (var queryFunc = CefV8Value.CreateFunction(_config.JSQueryFunction, handler)) { window.SetValue(_config.JSQueryFunction, queryFunc, attributes); } // Add the cancel function. using (var cancelFunc = CefV8Value.CreateFunction(_config.JSCancelFunction, handler)) { window.SetValue(_config.JSCancelFunction, cancelFunc, attributes); } } }
public void Bind(CefV8Value cefV8Value) { using (var func = CefV8Value.CreateFunction(descriptor.Name, new FunctionHandler(objectId, descriptor, v8Serializer, functionCallRegistry))) { cefV8Value.SetValue(descriptor.Name, func); } }
// 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 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); }
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { /*缓存数据库*/ string extensionCode = "var cachedb;" + "if(!cachedb)" + " cachedb={};"+ "(function() {" + " cachedb.Connect = function(dbName) {" + " native function Connect(dbName);"+ " return Connect(dbName);"+ " };" + " cachedb.Execute = function(commandText) {" + " native function Execute(commandText);"+ " return Execute(commandText);"+ " };" + " cachedb.Query = function(commandText) {" + " native function Query(commandText);"+ " return Query(commandText);"+ " };" + " cachedb.Close = function() {" + " native function Close();"+ " return Close();"+ " };" + "})();"; CefV8Handler ExtendsionHandler = new CwbJsExtendHandler(browser); CefRuntime.RegisterExtension("v8/cachedb", extensionCode, ExtendsionHandler); /*屏幕分辨率设置*/ int w = webBrowser.screenWidth; int h = webBrowser.screenHeight; if (w > 0 && h > 0) { string jscode = "Object.defineProperty(window.screen, 'height', {" + " get: function() {" + " return " + h + ";" + " }" + "});" + "Object.defineProperty(window.screen, 'width', {" + " get: function() {" + " return " + w + ";" + " }" + "});"; frame.ExecuteJavaScript(jscode, frame.Url, 0); } /*注册执行C#方法*/ CefV8Value globalValue = context.GetGlobal(); CefV8Handler callHandler = new CwbJsExtendHandler(browser); CefV8Value callMethod = CefV8Value.CreateFunction("CallCSharpMethod", callHandler); globalValue.SetValue("CallCSharpMethod", callMethod, CefV8PropertyAttribute.None); base.OnContextCreated(browser, frame, context); }
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); }
public CefV8Value CreateObject() { V8Value = CefV8Value.CreateObject(); V8Value.SetValue("log", CefV8Value.CreateFunction("log", V8Handler), CefV8PropertyAttribute.None); return(V8Value); }
/// <summary> /// This method returns a promise. The fulfiller function of that promise starts off the RFC chain /// to display an Open File dialog and return the value. /// </summary> protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) { var fulfiller = CefV8Value.CreateFunction("(anonymous)", new PendingPromiseFulfiller(pendingPromises)); returnValue = promiseFactory.CreatePromise(fulfiller); exception = null !; return(true); }
public static void Bind(this CefV8Value @this, string functionname, IWebView iCefV8Context, Action <string, CefV8Value, CefV8Value[]> iaction) { iCefV8Context.RunAsync(() => { var function = CefV8Value.CreateFunction(functionname, new CefV8Handler_Action(iaction)); @this.SetValue(functionname, function, CefV8PropertyAttribute.None); }); }
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { CefV8Value global = context.GetGlobal(); CefV8Value func = CefV8Value.CreateFunction("magic", new V8Handler()); global.SetValue("magic", func, CefV8PropertyAttribute.None); base.OnContextCreated(browser, frame, context); }
private void CreateFunction(CefV8Value parent, CefV8Handler method, String name) { // Create the {name} function. CefV8Value value = CefV8Value.CreateFunction(name, method); // Add the {name} function to the {parent} object. parent.SetValue(name, value, CefV8PropertyAttribute.None); }
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)); }
/// <summary> /// 创建JavaScript方法 /// </summary> /// <param name="handler">处理程序</param> /// <param name="javascriptObject">经过V8 JS引擎处理后的对象</param> /// <param name="methodNames">方法键值对集合</param> public static void CreateJavascriptMethods(CefV8Handler handler, CefV8Value javascriptWrapper, IList <String> methodNames) { var unmanagedWrapper = (UnmanagedWrapper)(javascriptWrapper.GetUserData()); foreach (string methodName in methodNames) { string jsMethodName = LowercaseFirst(methodName); //unmanagedWrapper.AddMethodMapping(methodName, jsMethodName); javascriptWrapper.SetValue(jsMethodName, CefV8Value.CreateFunction(jsMethodName, handler), CefV8PropertyAttribute.None); } }
/// <summary> /// Execute the delegated code asynchronously. /// </summary> protected override bool Execute(string name, CefV8Value obj, CefV8Value[] arguments, out CefV8Value returnValue, out string exception) { // Create the promise fulfiller. var oArgs = ValueConverter.ConvertFromJsValues(arguments); var fulfiller = CefV8Value.CreateFunction("(anonymous)", new ThreadPoolFulfiller(func, oArgs)); // create the promise object returnValue = promiseFactory.CreatePromise(fulfiller); exception = null !; return(true); }
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); } }
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); }
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { if (frame.IsMain) { // Retrieve the context's window object and install the "cefReportDocumentSize" function // used to tell the node about the document size. using (var window = context.GetGlobal()) { var handler = new CustomCallbackHandler(browser, frame); var reportDocumentSizeFunc = CefV8Value.CreateFunction(CustomCallbackHandler.ReportDocumentSize, handler); window.SetValue(CustomCallbackHandler.ReportDocumentSize, reportDocumentSizeFunc, CefV8PropertyAttribute.None); } } base.OnContextCreated(browser, frame, context); }
/// <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> /// Call from CefRenderProcessHandler::OnContextCreated. Registers the /// JavaScripts functions with the new context. /// </summary> public void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { Helpers.RequireRendererThread(); // Register function handlers with the 'window' object. var window = context.GetGlobal(); var handler = new V8HandlerImpl(this, _config); CefV8PropertyAttribute attributes = CefV8PropertyAttribute.ReadOnly | CefV8PropertyAttribute.DontEnum | CefV8PropertyAttribute.DontDelete; // Add the query function. var queryFunc = CefV8Value.CreateFunction(_config.JSQueryFunction, handler); window.SetValue(_config.JSQueryFunction, queryFunc, attributes); // Add the cancel function. var cancelFunc = CefV8Value.CreateFunction(_config.JSCancelFunction, handler); window.SetValue(_config.JSCancelFunction, cancelFunc, attributes); }
/// <summary> /// Add a synchronous method to the supplied JavaScript object. /// </summary> /// <param name="jsObject"></param> /// <param name="functionName"></param> /// <param name="func"></param> private void RegisterFunction(CefV8Value jsObject, string functionName, Func <CefV8Value[], CefV8Value> func) { var handler = CefV8Value.CreateFunction(functionName, new HandlerProxy(func)); jsObject.SetValue(functionName, handler); }
private void RegisterAsyncFunction(CefV8Value jsObject, string functionName, CefV8Handler handler) { jsObject.SetValue(functionName, CefV8Value.CreateFunction(functionName, handler)); }
/// <summary> /// Add an asynchronous method to the supplied JavaScript object /// </summary> /// <param name="jsObject"></param> /// <param name="functionName"></param> /// <param name="func"></param> private void RegisterAsyncFunction(CefV8Value jsObject, string functionName, Delegate func) { var handler = CefV8Value.CreateFunction(functionName, new AsyncHandlerProxy(func, this.promiseFactory)); jsObject.SetValue(functionName, handler); }
private void RegisterFunction(CefV8Value jsObject, string functionName, Delegate func) { jsObject.SetValue(functionName, CefV8Value.CreateFunction(functionName, new HandlerProxy(func))); }
private static ICefV8Value CreateFunctionValue(string s, ICefV8Handler cefV8Handler) { return(new CefV8ValueImpl(CefV8Value.CreateFunction(s, new CefV8HandlerImpl(cefV8Handler)))); }
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); } }
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); }
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); } }
protected override void OnContextCreated(CefBrowser browser, CefFrame frame, CefV8Context context) { if (frame.IsMain) { // Retrieve the context's window object and install the "vvvvReportDocumentSize" function // used to tell the node about the document size as well as the "vvvvSend" function // used to tell the node about variables computed inside the frame. using (var window = context.GetGlobal()) { var handler = new CustomCallbackHandler(browser, frame); var reportDocumentSizeFunc = CefV8Value.CreateFunction(CustomCallbackHandler.ReportDocumentSize, handler); window.SetValue(CustomCallbackHandler.ReportDocumentSize, reportDocumentSizeFunc); window.SetValue("vvvvQuery", CefV8Value.CreateFunction("vvvvQuery", new DelegatingHandler((name, obj, args) => { const string argForm = "{ request: 'NAME', arguments: {}, onSuccess: function(response) {}, onError: function(error_message) {} }"; string invalidArg = $"vvvvQuery expects one argument of the form {argForm}"; if (args.Length != 1) { throw new Exception($"vvvvQuery expects one argument"); } var x = args[0]; if (x is null || !x.IsObject) { throw new Exception($"The argument must be of the form {argForm}"); } var requestValue = x.GetValue("request"); if (requestValue.IsUndefined) { throw new Exception($"The request entry is missing"); } if (!requestValue.IsString) { throw new Exception($"The request must be a string"); } var onSuccessValue = x.GetValue("onSuccess"); if (!onSuccessValue.IsUndefined && !onSuccessValue.IsFunction) { throw new Exception($"The onSuccess entry must be a function"); } var onErrorValue = x.GetValue("onError"); if (!onErrorValue.IsUndefined && !onErrorValue.IsFunction) { throw new Exception($"The onError entry must be a function"); } var request = requestValue.GetStringValue(); var id = queryCount++; if (queries.TryAdd((request, id), (context, onSuccessValue, onErrorValue))) { using var message = CefProcessMessage.Create("query-request"); message.Arguments.SetString(0, request); message.Arguments.SetInt(1, id); message.Arguments.SetValue(2, ToValue(x.GetValue("arguments"))); frame.SendProcessMessage(CefProcessId.Browser, message); } return(default);