예제 #1
0
 private JSValue Fib_1 (JSFunction function, JSObject @this, JSValue [] args)
 {
     return args[0].NumberValue <= 1 ? new JSValue (@this.Context, 1) : new JSValue (@this.Context,
         Fib_1 (function, @this, new [] { new JSValue (@this.Context, args[0].NumberValue - 1) }).NumberValue +
         Fib_1 (function, @this, new [] { new JSValue (@this.Context, args[0].NumberValue - 2) }).NumberValue
     );
 }
예제 #2
0
        /// <summary>
        /// Constructs a new NotificationHandler listening for websocket requests at a specified URL
        /// </summary>
        /// <param name="URL">the URL at which the Websocket Response will be available at</param>
        /// <param name="notifyForKeepalives">shall the OnNotification event be fired if the Notification is just a KeepAliveMessage</param>
        /// <param name="externalEndpoint">at which IP-Address and port is the server at for the client?</param>
        /// <param name="traceMessagesClient">shall the communication be logged in the client browser console? (for debugging)</param>
        /// <param name="maximumLastMessageTime">the maximum time at which the server decides not to sent a keepalive package after not hearing from the client. (null means DefaultMaximumLastMessageTime)</param>
        public NotificationHandler(string URL, bool notifyForKeepalives = false, IPEndPoint externalEndpoint = null, bool traceMessagesClient = false, TimeSpan?maximumLastMessageTime = null) : base(URL)
        {
            if (maximumLastMessageTime.HasValue)
            {
                MaximumLastMessageTime = maximumLastMessageTime.Value;
            }

            NotifyForKeepalives = notifyForKeepalives;
            TraceMessagesClient = traceMessagesClient;

            this._externalEndpoint = externalEndpoint;

            OnMessage    += (input, proxy) => HandleResponse(new NotificationResponse(input, proxy, URL, this));
            OnConnect    += proxy => Connect(proxy);
            OnDisconnect += proxy => Disconnect(proxy);

            string methodName = NotificationHelper.GetFunctionName(ID);

            SendingFunction = new JSFunction(methodName);

            AllNotificationHandlerMutex.WaitOne();
            AllNotificationHandlers.Add(this);
            AllNotificationHandlerMutex.ReleaseMutex();
        }
예제 #3
0
        /// <summary>
        /// 创建多维度钻取的函数
        /// </summary>
        /// <param name="pAjaxHandlerUrl"></param>
        /// <param name="pFunctionName"></param>
        /// <param name="pLoadingMessage"></param>
        /// <returns></returns>
        public static JSFunction CreateMultiDimDrillingFunction(string pAjaxHandlerUrl, string pFunctionName = "__fnAnalysisReportMultiDrill", string pLoadingMessage = "数据加载中,请稍后...")
        {
            JSFunction script = new JSFunction();

            script.Type         = JSFunctionTypes.Common;
            script.FunctionName = pFunctionName;
            //定义函数的参数列表
            script.Params = new List <string>();
            script.Params.Add("pDrillings");
            //参数检查
            script.AddSentence("if(pDrillings==null || pDrillings.length<=0){");
            script.AddSentence("    return;");
            script.AddSentence("}");
            //阴影遮罩
            script.AddSentence("var mask=new Ext.LoadMask(Ext.getBody(),{");
            script.AddSentence("{0}msg:'{1}'", Keyboard.TAB, pLoadingMessage);
            script.AddSentence("});");
            //开启遮罩
            script.AddSentence("mask.show();");
            //执行Ajax请求
            script.AddSentence("Ext.Ajax.request({");
            script.AddSentence("{0}url:'{1}'", Keyboard.TAB, pAjaxHandlerUrl);
            script.AddSentence("{0},params:Ext.JSON.encode(pDrillings)", Keyboard.TAB);
            script.AddSentence("{0},method:'POST'", Keyboard.TAB);
            script.AddSentence("{0},callback:function(options,success,response){{", Keyboard.TAB);
            script.AddSentence("{0}{0}if(success){{", Keyboard.TAB);
            script.AddSentence("{0}{0}{0}eval(response.responseText);", Keyboard.TAB);
            script.AddSentence("{0}{0}}}else{{", Keyboard.TAB);
            script.AddSentence("{0}{0}{0}alert('请求失败.');", Keyboard.TAB);
            script.AddSentence("{0}{0}}}", Keyboard.TAB);
            script.AddSentence("{0}{0}mask.hide();", Keyboard.TAB);
            script.AddSentence("{0}}}", Keyboard.TAB);
            script.AddSentence("});");
            //返回
            return(script);
        }
        public void LoadModuleScript(string name, string url, JSFunction success, JSFunction error)
        {
            Device.BeginInvokeOnMainThread(async() => {
                try {
                    string script = await Client.GetStringAsync(url);

                    success.Call(null, new Java.Lang.Object[] { new JSClrFunction(Engine, (args) =>
                        {
                            Execute(script, url);

                            return(new JSValue(Engine));
                        }) });
                }
                catch (JSException ex) {
                    var msg = $"Failed to load url {url}\r\n{ex.Stack()}\r\n{ex}";
                    System.Diagnostics.Debug.WriteLine(msg);
                    error.Call(null, new Java.Lang.Object[] { msg });
                } catch (Exception ex) {
                    var msg = $"Failed to load url {url}\r\n{ex}";
                    System.Diagnostics.Debug.WriteLine(msg);
                    error.Call(null, new Java.Lang.Object[] { msg });
                }
            });
        }
예제 #5
0
 public void TestRecursionNoScript()
 {
     var fib = new JSFunction (context, null, Fib_1);
     for (int i = 0; i <= 25; i++) {
         Assert.AreEqual (Fib_2 (i), fib.CallAsFunction (null, new [] { new JSValue (context, i) }).NumberValue);
     }
 }
        // Handler of the external.app.performHeavyWork method.
        private void OnWork(object sender, JavascriptMethodEventArgs e)
        {
            // Must have 2 arguments passed.
            if (e.Arguments.Length != 3)
            {
                return;
            }

            // Must be a function object.
            if (!e.Arguments[0].IsFunctionObject)
            {
                return;
            }

            // Must be a timeout value.
            if (!e.Arguments[1].IsNumber)
            {
                return;
            }

            // Must be the image id.
            if (!e.Arguments[2].IsNumber)
            {
                return;
            }

            // Get the NavigationInterceptor. This will allow us to cancel the operation
            // if the user navigates away.
            INavigationInterceptor navigationInterceptor = webControl.GetService(typeof(INavigationInterceptor)) as INavigationInterceptor;

            // Without this, do not proceed.
            if (navigationInterceptor == null)
            {
                return;
            }

            // You can cache the callback and call it only when your application
            // has performed all work necessary and has a result ready to send.
            // Note that this callback object is valid for as long as the current
            // page is loaded; a navigation will invalidate it. This is why we
            // need the NavigationInterceptor service acquired above.
            JSFunction callbackArg = e.Arguments[0];
            // Get the image id.
            int id = (int)e.Arguments[1];
            // Get the timeout specified.
            int timeout = (int)e.Arguments[2];

            // Make sure it's a function object.
            if (!callbackArg)
            {
                return;
            }

            // See it!
            Debug.Print(callbackArg.ToString());

            // You need to copy the object if you intend to cache it. The original
            // object argument passed to the handler is destroyed by default when
            // the handler returns. A copy will keep it alive. Note that the clone
            // of a JSFunction, will definitely be a JSFunction as well.
            JSFunction callback = (JSFunction)callbackArg.Clone();

            // Create a state object. This holds the callback and controls
            // cancellation. It is passed to both the background operation procedure
            // and the response procedure.
            JavascriptCallbackState state = new JavascriptCallbackState(navigationInterceptor, callback, id, timeout);

            // Perform your heavy work.
            Task.Factory.StartNew(
                /* The function that will perform the work. */
                (Func <Object, String>)PerformWork,
                /* Pass the state object. */
                state,

                /* The CancellationToken that will let us know if we
                 * should cancel passing back the result. */
                state.Token).ContinueWith(
                /* Send the result when complete. */
                SendResponse,

                /* Make sure the result is sent on the
                 * initial thread. */
                TaskScheduler.FromCurrentSynchronizationContext());
        }
예제 #7
0
        public BrowserForm()
        {
            InitializeComponent();

            LogWriteLine("CfxRuntime.ApiHash(0): " + CfxRuntime.ApiHash(0));
            LogWriteLine("CfxRuntime.ApiHash(1): " + CfxRuntime.ApiHash(1));
            LogWriteLine("CfxRuntime.GetCefVersion(): " + CfxRuntime.GetCefVersion());
            LogWriteLine("CfxRuntime.GetChromeVersion(): " + CfxRuntime.GetChromeVersion());
            LogWriteLine("Platform OS: {0}; Arch: {1}", CfxRuntime.PlatformOS, CfxRuntime.PlatformArch);
            LogWriteLine();

            ChromiumWebBrowser.RemoteProcessCreated += (e) => {
                LogWriteLine("Remote render process created with process id {0}", CfxRemoteCallContext.CurrentContext.ProcessId, CfxRemoteCallContext.CurrentContext.ThreadId);
                e.RenderProcessHandler.OnRenderThreadCreated += (s, e1) => {
                    LogWriteLine("RenderProcessHandler.OnRenderThreadCreated, process id = {0}", CfxRemoteCallContext.CurrentContext.ProcessId);
                };
                e.RenderProcessHandler.OnBrowserDestroyed += (s, e1) => {
                    // this is never reached.
                    LogWriteLine("RenderProcessHandler.OnBrowserDestroyed, process id = {0}, browser id = {1}", CfxRemoteCallContext.CurrentContext.ProcessId, e1.Browser.Identifier);
                };
                e.RenderProcessHandler.OnBrowserCreated += (s, e1) => {
                    LogWriteLine("RenderProcessHandler.OnBrowserCreated, process id = {0}, browser id = {1}", CfxRemoteCallContext.CurrentContext.ProcessId, e1.Browser.Identifier);
                };
                e.RenderProcessHandler.OnFocusedNodeChanged += (s, e1) => {
                    LogWriteLine("RenderProcessHandler.OnFocusedNodeChanged, process id = {0}, browser id = {1}, node = {2}", CfxRemoteCallContext.CurrentContext.ProcessId, e1.Browser.Identifier, e1.Node?.Name);
                };
            };

            LoadUrlButton.Click += new EventHandler(LoadUrlButton_Click);
            UrlTextBox.KeyDown  += new KeyEventHandler(UrlTextBox_KeyDown);

            JSHelloWorldButton.Click += new EventHandler(JSHelloWorldButton_Click);
            JSTestPageButton.Click   += new EventHandler(TestButton_Click);
            VisitDomButton.Click     += new EventHandler(VisitDomButton_Click);

            WebBrowser.GlobalObject.AddFunction("CfxHelloWorld").Execute      += CfxHelloWorld_Execute;
            WebBrowser.GlobalObject.AddFunction("testDoubleCallback").Execute += TestDoubleCallback_Execute;

            // related to issue #65
            WebBrowser.GlobalObject.AddFunction("ArrayTestCallback").Execute += (s, e1) => {
                var array = e1.Arguments[0];
                var v0    = array.GetValue(0);
                var v1    = array.GetValue(1);
                if (v0 != null)
                {
                    LogWriteLine("Array test function works: v0 = {0}, v1 = {1}", v0.IntValue, v1.IntValue);
                }
                else
                {
                    LogWriteLine("Array test function: array is broken.");
                }
            };

            // related to pull request #1
            WebBrowser.GlobalObject.AddFunction("ListKeysInDocumentObject").Execute += (s, e1) => {
                var           doc  = e1.Arguments[0];
                List <string> keys = new List <string>();
                if (doc.GetKeys(keys))
                {
                    LogWriteLine("document has {0} keys:", keys.Count);
                    keys.ForEach(k => LogWriteLine(k));
                }
                else
                {
                    LogWriteLine("GetKeys returned false.");
                }
            };

            WebBrowser.GlobalObject.Add("TestObject", new JsTestObject(this));


            var sleepFunction = new JSFunction(JSInvokeMode.DontInvoke);

            sleepFunction.Execute += (s, e) => {
                LogWriteLine("Sleep function: sleep 5 seconds...");
                Thread.Sleep(5000);
                try {
                    var x = e.Arguments[0].IntValue;
                    LogWriteLine("Sleep function: Event args accessed sucessfully.");
                } catch (Exception ex) {
                    LogWriteLine("Sleep function: Error accessing event args:");
                    LogWriteLine(ex.ToString());
                }
            };

            WebBrowser.GlobalObject.Add("SleepFunction", sleepFunction);

            var html = @"

                <html>
                <head><script>
                    function testlog(text) {
                        document.getElementById('testfunc_result').innerHTML += '<br>' + text;
                    }
                </script>
                <script>
                    function doubleCallback(arg1, arg2) {
                        testlog('Function doubleCallback() called. Arguments:');
                        testlog(arg1);
                        testlog(arg2);
                        return 'This text is returned from doubleCallback()';
                    }
                    function clearTestLog() {
                        document.getElementById('testfunc_result').innerHTML = '';
                    }
                </script>
                </head>
                <body>
                    <br><br><b>Local resource/javascript integration test page.</b>
                    <hr><br><br>
                    Local resource image:<br>
                    <img src='http://localresource/image'><br><br>
                    <a href='http://www.google.com/' onclick=""window.open('http://www.google.com/', 'Popup test', 'width=800,height=600,scrollbars=yes'); return false;"">open popup window.open</a>
                    <a href='http://www.google.com/' target=blank>open popup target=blank</a>
                    <br><br>
                    <button id='testbutton1' onclick=""document.getElementById('testfunc_result').innerHTML += '<br>' + CfxHelloWorld('this is the hello world function');"">Execute CfxHelloWorld()</button>
                    <button id='testbutton2' onclick=""
                        testlog('TestObject = ' + TestObject);
                        testlog('TestObject.testFunction = ' + TestObject.testFunction);
                        TestObject.testFunction('this is the test function');
                    "">Execute TestObject.testFunction()</button>
                    <button id='testbutton3' onclick=""
                        testlog('TestObject = ' + TestObject);
                        testlog('TestObject.anotherObject = ' + TestObject.anotherObject);
                        testlog('TestObject.anotherObject.anotherTestFunction = ' + TestObject.anotherObject.anotherTestFunction);
                        testlog(TestObject.anotherObject.anotherTestFunction('this is the other test function'));
                    "">Execute TestObject.anotherObject.anotherTestFunction()</button>
                    <button id='testbutton4' onclick=""
                        testlog('TestObject.dynamicProperty = ' + TestObject.dynamicProperty);
                        testlog('(define TestObject.dynamicProperty += 100)');
                        TestObject.dynamicProperty += 100;
                        testlog('TestObject.dynamicProperty = ' + TestObject.dynamicProperty);
                    "">Defined TestObject properties</button>
                    <button id='testbutton5' onclick=""
                        testlog('TestObject.foo = ' + TestObject.foo);
                        testlog('(define TestObject.foo = 100)');
                        TestObject.foo = 100;
                        testlog('TestObject.foo = ' + TestObject.foo);
                    "">Undefined TestObject properties</button>
                    <button id='testbutton6' onclick=""
                        testlog('Call native function testDoubleCallback(doubleCallback). Return value:');
                        testlog('Return value: ' + testDoubleCallback(doubleCallback));
                    "">Double Callback</button>
                    <br><br><div id='testfunc_result'></div>
            ";

            WebBrowser.SetWebResource("http://localresource/text.html", new Chromium.WebBrowser.WebResource(html));

            var bm = new System.Drawing.Bitmap(100, 100);

            using (var g = System.Drawing.Graphics.FromImage(bm)) {
                g.FillRectangle(System.Drawing.Brushes.Yellow, 0, 0, 99, 99);
                g.DrawRectangle(System.Drawing.Pens.Black, 0, 0, 99, 99);
                g.DrawLine(System.Drawing.Pens.Black, 0, 0, 99, 99);
            }
            WebBrowser.SetWebResource("http://localresource/image", new Chromium.WebBrowser.WebResource(bm));

            WebBrowser.DisplayHandler.OnConsoleMessage += (s, e) => LogCallback(s, e);
            WebBrowser.DisplayHandler.OnTitleChange    += (s, e) => LogCallback(s, e);
            WebBrowser.DisplayHandler.OnStatusMessage  += (s, e) => LogCallback(s, e);

            WebBrowser.DisplayHandler.OnTitleChange += (s, e) => {
                var wb = ChromiumWebBrowser.FromCfxBrowser(e.Browser);
                LogWriteLine("ChromiumWebBrowser.FromCfxBrowser(e.Browser) == WebBrowser: {0}", wb == WebBrowser);
                var title = e.Title;
                BeginInvoke((MethodInvoker)(() => Text = "ChromiumWebBrowser - " + title));
            };

            WebBrowser.LifeSpanHandler.OnBeforePopup += (s, e) => {
                LogCallback(s, e);
            };

            WebBrowser.LoadHandler.OnLoadingStateChange += (s, e) => {
                if (e.IsLoading)
                {
                    return;
                }
                BeginInvoke((MethodInvoker)(() => {
                    UrlTextBox.Text = WebBrowser.Url.ToString();
                }));
            };

            WebBrowser.LoadUrl("http://localresource/text.html");

            WebBrowser.FindToolbar.Visible = true;

            WebBrowser.OnV8ContextCreated += (s, e) => {
                if (e.Frame.IsMain)
                {
                    CfrV8Value     retval;
                    CfrV8Exception exception;
                    if (e.Context.Eval("CfxHelloWorld()", null, 0, out retval, out exception))
                    {
                        LogWriteLine("OnV8ContextCreated: Eval succeeded, retval is '{0}'", retval.StringValue);
                    }
                    else
                    {
                        LogWriteLine("OnV8ContextCreated: Eval failed, exception is '{0}'", exception.Message);
                    }
                }
            };

            WebBrowser.GlobalObject.AddFunction("SubmitAsyncTestFunction").Execute += JS_SubmitAsyncTestFunction;
            WebBrowser.GlobalObject.AddFunction("bigStringFunction").Execute       += JS_bigStringFunction;
        }
예제 #8
0
 /// <summary>
 /// Returns a JavaScript V8Function object instance associated with this function template.
 /// There can only ever be ONE V8 function object per V8 function template in a single V8 JavaScript context;
 /// however, V8.NET does allow one MANAGED function type per managed template. In this case, a single call triggers all derived types at once.
 /// The first callback to return a value terminates the cycle and any following callbacks are ignored.
 /// <para>WARNING: The returned function object will be garbage collected if you don't store the reference anywhere. If this happens, then calling
 /// the function object in JavaScript will return "undefined". This is because function object callbacks are dynamic and are only valid when
 /// the calling object is still in use.</para>
 /// </summary>
 /// <param name="callback">When a new instance of V8Function is created, it's 'Callback' property will set to the specified value.
 /// If you don't provide a callback, then calling the function in JavaScript will simply do nothing and return "undefined".</param>
 public V8Function GetFunctionObject(JSFunction callback)
 {
     return(GetFunctionObject <V8Function>(callback));
 }
예제 #9
0
 public virtual bool IsInstanceOf(JSFunction constructor)
 {
     Contract.Requires(constructor != null);
     throw new TypeErrorException();
 }
예제 #10
0
 private V8Function GetFunctionWrapper(JSFunction callback)
 {
     return(_engine.CreateFunctionTemplate().GetFunctionObject(callback));
 }
예제 #11
0
        public void Invoke(HttpClient client, string url, JSObject ajaxOptions, JSFunction success, JSFunction failed, JSFunction progress)
        {
            Device.BeginInvokeOnMainThread(async() => {
                try {
                    string method  = ajaxOptions.GetJSPropertyValue("method").ToString().ToLower();
                    var m          = HttpMethod.Get;
                    HttpContent hc = null;
                    switch (method)
                    {
                    case "post":
                        m  = HttpMethod.Post;
                        hc = CreateContent(ajaxOptions);
                        break;

                    case "put":
                        m  = HttpMethod.Put;
                        hc = CreateContent(ajaxOptions);
                        break;

                    case "delete":
                        m  = HttpMethod.Delete;
                        hc = CreateContent(ajaxOptions);
                        break;

                    case "head":
                        m = HttpMethod.Head;
                        break;

                    case "options":
                        m = HttpMethod.Options;
                        break;
                    }

                    var msg     = new HttpRequestMessage(m, url);
                    msg.Content = hc;
                    var res     = await client.SendAsync(msg, HttpCompletionOption.ResponseHeadersRead);

                    ajaxOptions.SetJSPropertyValue("status", (int)res.StatusCode);
                    var ct = res.Content.Headers.ContentType?.ToString();
                    if (ct != null)
                    {
                        ajaxOptions.SetJSPropertyValue("responseType", ct);
                    }

                    //if (!res.IsSuccessStatusCode) {
                    //    string error = await res.Content.ReadAsStringAsync();
                    //    ajaxOptions.SetJSPropertyValue("responseText", error);
                    //    success.Call(null, new Java.Lang.Object[] { error });
                    //    return;
                    //}

                    string text = await res.Content.ReadAsStringAsync();
                    ajaxOptions.SetJSPropertyValue("responseText", text);
                    success.Call(null, new Java.Lang.Object[] { ajaxOptions });
                }
                catch (Exception ex) {
                    failed.Call(null, new Java.Lang.Object[] { ex.ToString() });
                }
            });
        }
예제 #12
0
 public void RegisterInvokeHandler(JSFunction callback)
 {
 }
예제 #13
0
 private V8Function GetFunctionWrapper(JSFunction callback)
 {
     return _engine.CreateFunctionTemplate().GetFunctionObject(callback);
 }
        public JSDisposable WatchProperty(JSWrapper objTarget, string name, JSValue events, JSFunction callback)
        {
            object obj = objTarget.As <object>();

            if (obj is INotifyPropertyChanged element)
            {
                var pinfo = obj.GetProperty(name);

                PropertyChangedEventHandler handler = (s, e) =>
                {
                    if (e.PropertyName == name)
                    {
                        var value = pinfo.GetValue(obj);
                        callback.Call(null, new Java.Lang.Object[] { value.Wrap(Engine) });
                    }
                };

                element.PropertyChanged += handler;
                return(new JSDisposable(Engine, () =>
                {
                    element.PropertyChanged -= handler;
                }));
            }

            return(new JSDisposable(Engine, () => { }));
        }
        public void Ajax(string url, JSObject ajaxOptions, JSFunction success, JSFunction failed, JSFunction progress)
        {
            var client  = this.Client;
            var service = AjaxService.Instance;

            service.Invoke(client, url, ajaxOptions, success, failed, progress);
        }