diff --git a/CefSharp.Example/Resources/ScriptedMethodsTest.html b/CefSharp.Example/Resources/ScriptedMethodsTest.html index f53def8c8..43fbc47a6 100644 --- a/CefSharp.Example/Resources/ScriptedMethodsTest.html +++ b/CefSharp.Example/Resources/ScriptedMethodsTest.html @@ -18,7 +18,7 @@

Asynchronous events from the Javascript environment.

Sending events from the Javascript environment to a .Net class involves the following:

@@ -33,17 +33,17 @@
             (function () {
                 var counter = 0;
-	            var elem = document.getElementById('test-button');
+                var elem = document.getElementById('test-button');
                 elem.removeAttribute('disabled');
-	            elem.addEventListener('click', function(e){
-		            if (!window.boundEvent){
-			            console.log('window.boundEvent does not exist.');
-			            return;
-		            }
+                elem.addEventListener('click', function(e){
+                    if (!window.boundEvent){
+                        console.log('window.boundEvent does not exist.');
+                        return;
+                    }
                     counter++;
-            		window.boundEvent.raiseEvent('click', {count: counter, id: e.target.id, tagName: e.target.tagName});
-	            });
-	            console.log(`Added click listener to ${elem.id}.`);
+                    window.boundEvent.raiseEvent('click', {count: counter, id: e.target.id, tagName: e.target.tagName});
+                });
+                console.log(`Added click listener to ${elem.id}.`);
             })();
         
diff --git a/CefSharp.Example/ScriptedMethods.cs b/CefSharp.Example/ScriptedMethods.cs index a0323ba69..0e68e2b49 100644 --- a/CefSharp.Example/ScriptedMethods.cs +++ b/CefSharp.Example/ScriptedMethods.cs @@ -3,9 +3,6 @@ // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -15,18 +12,14 @@ namespace CefSharp.Example /// Methods whose functionaity is mostly implemented by evaluating or /// executing scripts in the browser. /// - public class ScriptedMethods + public static class ScriptedMethods { /// /// Determine if the active element in a frame accepts text input. /// - /// - /// Test the active element in this frame. - /// - /// - /// True if the active element accepts text input. - /// - public static async Task ActiveElementAcceptsTextInput(IFrame frame) + /// Test the active element in this frame. + /// True if the active element accepts text input. + public static async Task ActiveElementAcceptsTextInput(this IFrame frame) { if (frame == null) { @@ -35,26 +28,27 @@ namespace CefSharp.Example // Scripts should be minified for production builds. The script // could also be read from a file... - var script = - "(function () {" + - " var isText = false;" + - " var activeElement = document.activeElement;" + - " if (activeElement) {" + - " if (activeElement.tagName.toLowerCase() === 'textarea') {" + - " isText = true;" + - " } else {" + - " if (activeElement.tagName.toLowerCase() === 'input') {" + - " if (activeElement.hasAttribute('type')) {" + - " var inputType = activeElement.getAttribute('type').toLowerCase();" + - " if (inputType === 'text' || inputType === 'email' || inputType === 'password' || inputType === 'tel' || inputType === 'number' || inputType === 'range' || inputType === 'search' || inputType === 'url') {" + - " isText = true;" + - " }" + - " }" + - " }" + - " }" + - " }" + - " return isText;" + - "})();"; + const string script = + @"(function () + { + var isText = false; + var activeElement = document.activeElement; + if (activeElement) { + if (activeElement.tagName.toLowerCase() === 'textarea') { + isText = true; + } else { + if (activeElement.tagName.toLowerCase() === 'input') { + if (activeElement.hasAttribute('type')) { + var inputType = activeElement.getAttribute('type').toLowerCase(); + if (inputType === 'text' || inputType === 'email' || inputType === 'password' || inputType === 'tel' || inputType === 'number' || inputType === 'range' || inputType === 'search' || inputType === 'url') { + isText = true; + } + } + } + } + } + return isText; + })();"; var response = await frame.EvaluateScriptAsync(script); if (!response.Success) @@ -68,16 +62,10 @@ namespace CefSharp.Example /// /// Determine if the frame contains an element with the specified id. /// - /// - /// The id to find. - /// - /// - /// Test the elements in this frame. - /// - /// - /// True if an element with the specified id exists in the frame. - /// - public static async Task ElementWithIdExists(string id, IFrame frame) + /// Test the elements in this frame. + /// The id to find. + /// True if an element with the specified id exists in the frame. + public static async Task ElementWithIdExists(this IFrame frame, string id) { if (frame == null) { @@ -85,10 +73,10 @@ namespace CefSharp.Example } var script = - "(function () {" + - " var n = document.getElementById('##ID##');" + - " return n !== null && typeof n !== 'undefined';" + - "})();"; + @"(function () { + var n = document.getElementById('##ID##'); + return n !== null && typeof n !== 'undefined'; + })();"; // For simple inline scripts you could use String.Format() but // beware of braces in the javascript code. If reading from a file @@ -111,16 +99,10 @@ namespace CefSharp.Example /// event information to a .Net class bound to the browser. See /// ScriptedMethodsBoundObject. /// - /// - /// The id of an element that exists in the frame. - /// - /// - /// The element is in this frame. - /// - /// - /// Subscribe to this event. For example 'click'. - /// - public static void ListenForEvent(string id, IFrame frame, string eventName) + /// The element is in this frame. + /// The id of an element that exists in the frame. + /// Subscribe to this event. For example 'click'. + public static void ListenForEvent(this IFrame frame, string id, string eventName) { if (frame == null) { @@ -129,28 +111,29 @@ namespace CefSharp.Example // Adds a click event listener to a DOM element with the provided // ID. When the element is clicked the ScriptedMethodsBoundObject's - // raiseEvent function is invoked. This is one way to get + // RaiseEvent function is invoked. This is one way to get // asynchronous events from the web page. Typically though the web - // page would be aware of window.boundEvent.raiseEvent and would + // page would be aware of window.boundEvent.RaiseEvent and would // simply raise it as needed. // // Scripts should be minified for production builds. The script // could also be read from a file... var script = - "(function () {" + - " var counter = 0;" + - " var elem = document.getElementById('##ID##');" + - " elem.removeAttribute('disabled');" + - " elem.addEventListener('##EVENT##', function(e){" + - " if (!window.boundEvent){" + - " console.log('window.boundEvent does not exist.');" + - " return;" + - " }" + - " counter++;" + - " window.boundEvent.raiseEvent('##EVENT##', {count: counter, id: e.target.id, tagName: e.target.tagName});" + - " });" + - " console.log(`Added ##EVENT## listener to ${elem.id}.`);" + - "})();"; + @"(function () { + var counter = 0; + var elem = document.getElementById('##ID##'); + elem.removeAttribute('disabled'); + elem.addEventListener('##EVENT##', function(e){ + if (!window.boundEvent){ + console.log('window.boundEvent does not exist.'); + return; + } + counter++; + //NOTE RaiseEvent was converted to raiseEvent in JS (this is configurable when registering the object) + window.boundEvent.raiseEvent('##EVENT##', {count: counter, id: e.target.id, tagName: e.target.tagName}); + }); + console.log(`Added ##EVENT## listener to ${elem.id}.`); + })();"; // For simple inline scripts you could use String.Format() but // beware of braces in the javascript code. If reading from a file diff --git a/CefSharp.Example/ScriptedMethodsBoundObject.cs b/CefSharp.Example/ScriptedMethodsBoundObject.cs index e5e1183d9..42667426a 100644 --- a/CefSharp.Example/ScriptedMethodsBoundObject.cs +++ b/CefSharp.Example/ScriptedMethodsBoundObject.cs @@ -22,13 +22,13 @@ namespace CefSharp.Example /// invoked in the Javascript environment when some event of interest /// happens. /// - /// - /// The name of the event. - /// - /// - /// Data provided by the invoker pertaining to the event. - /// - public void raiseEvent (string eventName, object eventData = null) + /// The name of the event. + /// Data provided by the invoker pertaining to the event. + /// + /// By default RaiseEvent will be translated to raiseEvent as a javascript function. + /// This is configurable when calling RegisterJsObject by setting camelCaseJavascriptNames; + /// + public void RaiseEvent(string eventName, object eventData = null) { if (EventArrived != null) { diff --git a/CefSharp.WinForms.Example/BrowserForm.Designer.cs b/CefSharp.WinForms.Example/BrowserForm.Designer.cs index 4c10417c7..20038ab3e 100644 --- a/CefSharp.WinForms.Example/BrowserForm.Designer.cs +++ b/CefSharp.WinForms.Example/BrowserForm.Designer.cs @@ -292,7 +292,7 @@ this.doesElementWithIDExistToolStripMenuItem.Name = "doesElementWithIDExistToolStripMenuItem"; this.doesElementWithIDExistToolStripMenuItem.Size = new System.Drawing.Size(271, 22); this.doesElementWithIDExistToolStripMenuItem.Text = "Does element with ID exist"; - this.doesElementWithIDExistToolStripMenuItem.Click += new System.EventHandler(this.DoesElementWithIDExistToolStripMenuItemClick); + this.doesElementWithIDExistToolStripMenuItem.Click += new System.EventHandler(this.DoesElementWithIdExistToolStripMenuItemClick); // // listenForButtonClickToolStripMenuItem // diff --git a/CefSharp.WinForms.Example/BrowserForm.cs b/CefSharp.WinForms.Example/BrowserForm.cs index 45745cc18..f625bd3e3 100644 --- a/CefSharp.WinForms.Example/BrowserForm.cs +++ b/CefSharp.WinForms.Example/BrowserForm.cs @@ -306,66 +306,72 @@ namespace CefSharp.WinForms.Example if (control != null) { var frame = control.Browser.GetFocusedFrame(); - ScriptedMethods.ActiveElementAcceptsTextInput(frame) - .ContinueWith(task => + + //Execute extension method + frame.ActiveElementAcceptsTextInput().ContinueWith(task => + { + string message; + var icon = MessageBoxIcon.Information; + if (task.Exception == null) { - var message = String.Empty; - var icon = MessageBoxIcon.Information; - if (task.Exception != null) - { - message = String.Format("Script evaluation failed. {0}", task.Exception.Message); - icon = MessageBoxIcon.Error; - } - else - { - var isText = (bool)task.Result; - message = String.Format("The active element is{0}a text entry element.", isText ? " " : " not "); - } + var isText = task.Result; + message = string.Format("The active element is{0}a text entry element.", isText ? " " : " not "); + } + else + { + message = string.Format("Script evaluation failed. {0}", task.Exception.Message); + icon = MessageBoxIcon.Error; + } - MessageBox.Show(message, "Does active element accept text input", MessageBoxButtons.OK, icon); - }); + MessageBox.Show(message, "Does active element accept text input", MessageBoxButtons.OK, icon); + }); } } - private void DoesElementWithIDExistToolStripMenuItemClick(object sender, EventArgs e) + private void DoesElementWithIdExistToolStripMenuItemClick(object sender, EventArgs e) { // This is the main thread, it's safe to create and manipulate form // UI controls. - var dialog = new InputBox(); - dialog.Instructions = "Enter an element ID to find."; - dialog.Title = "Find an element with an ID"; - dialog.OnEvaluate += (senderDlg, eDlg) => - { - // This is also the main thread. - var control = GetCurrentTabControl(); - if (control != null) - { - var frame = control.Browser.GetFocusedFrame(); - ScriptedMethods.ElementWithIdExists(dialog.Value, frame) - .ContinueWith(task => - { - // Now we're not on the main thread, perhaps the - // Cef UI thread. It's not safe to work with - // form UI controls or to block this thread. - // Queue up a delegate to be executed on the - // main thread. - BeginInvoke(new Action(() => - { - var message = String.Empty; - if (task.Exception != null) - { - message = String.Format("Script evaluation failed. {0}", task.Exception.Message); - } - else - { - message = task.Result.ToString(); - } + var dialog = new InputBox + { + Instructions = "Enter an element ID to find.", + Title = "Find an element with an ID" + }; + + dialog.OnEvaluate += (senderDlg, eDlg) => + { + // This is also the main thread. + var control = GetCurrentTabControl(); + if (control != null) + { + var frame = control.Browser.GetFocusedFrame(); + + //Execute extension method + frame.ElementWithIdExists(dialog.Value).ContinueWith(task => + { + // Now we're not on the main thread, perhaps the + // Cef UI thread. It's not safe to work with + // form UI controls or to block this thread. + // Queue up a delegate to be executed on the + // main thread. + BeginInvoke(new Action(() => + { + string message; + if (task.Exception == null) + { + message = task.Result.ToString(); + } + else + { + message = string.Format("Script evaluation failed. {0}", task.Exception.Message); + } + + dialog.Result = message; + })); + }); + } + }; - dialog.Result = message; - })); - }); - } - }; dialog.Show(this); } @@ -384,7 +390,9 @@ namespace CefSharp.WinForms.Example if (control != null) { var frame = control.Browser.GetFocusedFrame(); - ScriptedMethods.ListenForEvent("test-button", frame, "click"); + + //Execute extension method + frame.ListenForEvent("test-button", "click"); } } } diff --git a/CefSharp.WinForms.Example/BrowserTabUserControl.cs b/CefSharp.WinForms.Example/BrowserTabUserControl.cs index f3d56a44e..c3f988264 100644 --- a/CefSharp.WinForms.Example/BrowserTabUserControl.cs +++ b/CefSharp.WinForms.Example/BrowserTabUserControl.cs @@ -51,7 +51,9 @@ namespace CefSharp.WinForms.Example var eventObject = new ScriptedMethodsBoundObject(); eventObject.EventArrived += OnJavascriptEventArrived; - browser.RegisterJsObject("boundEvent", eventObject); + // Use the default of camelCaseJavascriptNames + // .Net methods starting with a capitol will be translated to starting with a lower case letter when called from js + browser.RegisterJsObject("boundEvent", eventObject, camelCaseJavascriptNames:true); CefExample.RegisterTestResources(browser); @@ -92,20 +94,22 @@ namespace CefSharp.WinForms.Example this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = args.Address); } - private void OnJavascriptEventArrived(string eventName, object eventData) + private static void OnJavascriptEventArrived(string eventName, object eventData) { switch (eventName) { case "click": + { var message = eventData.ToString(); var dataDictionary = eventData as Dictionary; if (dataDictionary != null) { - var result = String.Join(", ", dataDictionary.Select, string>(pair => pair.Key + "=" + pair.Value)); - message = ("event data: " + result); + var result = string.Join(", ", dataDictionary.Select(pair => pair.Key + "=" + pair.Value)); + message = "event data: " + result; } MessageBox.Show(message, "Javascript event arrived", MessageBoxButtons.OK, MessageBoxIcon.Information); break; + } } }