diff --git a/CefSharp.Example/ScriptedMethods.cs b/CefSharp.Example/ScriptedMethods.cs index a9003476d..a0323ba69 100644 --- a/CefSharp.Example/ScriptedMethods.cs +++ b/CefSharp.Example/ScriptedMethods.cs @@ -11,8 +11,21 @@ using System.Threading.Tasks; namespace CefSharp.Example { + /// + /// Methods whose functionaity is mostly implemented by evaluating or + /// executing scripts in the browser. + /// public 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) { if (frame == null) @@ -52,6 +65,18 @@ namespace CefSharp.Example return (bool)response.Result; } + /// + /// 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) { if (frame == null) @@ -79,5 +104,62 @@ namespace CefSharp.Example return (bool)response.Result; } + + /// + /// Set an event listener on the element with the provided id. When the + /// event listener callback is invoked an attempt will be made to pass + /// 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) + { + if (frame == null) + { + throw new ArgumentException("An IFrame instance is required.", "frame"); + } + + // 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 + // asynchronous events from the web page. Typically though the web + // 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}.`);" + + "})();"; + + // For simple inline scripts you could use String.Format() but + // beware of braces in the javascript code. If reading from a file + // it's probably safer to include tokens that can be replaced via + // regex. + script = Regex.Replace(script, "##ID##", id); + script = Regex.Replace(script, "##EVENT##", eventName); + + frame.ExecuteJavaScriptAsync(script); + } } } diff --git a/CefSharp.Example/ScriptedMethodsBoundObject.cs b/CefSharp.Example/ScriptedMethodsBoundObject.cs new file mode 100644 index 000000000..e5e1183d9 --- /dev/null +++ b/CefSharp.Example/ScriptedMethodsBoundObject.cs @@ -0,0 +1,39 @@ +// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. +using System; + +namespace CefSharp.Example +{ + /// + /// A class that is used to demonstrate how asynchronous javascript events can be returned to the .Net runtime environment. + /// + /// + /// + public class ScriptedMethodsBoundObject + { + /// + /// Raised when a Javascript event arrives. + /// + public event Action EventArrived; + + /// + /// This method will be exposed to the Javascript environment. It is + /// 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) + { + if (EventArrived != null) + { + EventArrived(eventName, eventData); + } + } + } +} diff --git a/CefSharp.WinForms.Example/BrowserForm.Designer.cs b/CefSharp.WinForms.Example/BrowserForm.Designer.cs index 49bfe0168..4c10417c7 100644 --- a/CefSharp.WinForms.Example/BrowserForm.Designer.cs +++ b/CefSharp.WinForms.Example/BrowserForm.Designer.cs @@ -57,8 +57,11 @@ this.currentZoomLevelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.scriptToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.isTextInputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.browserTabControl = new System.Windows.Forms.TabControl(); this.doesElementWithIDExistToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.listenForButtonClickToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.goToDemoPageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.injectJavascriptCodeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.browserTabControl = new System.Windows.Forms.TabControl(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // @@ -271,7 +274,8 @@ // this.scriptToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.isTextInputToolStripMenuItem, - this.doesElementWithIDExistToolStripMenuItem}); + this.doesElementWithIDExistToolStripMenuItem, + this.listenForButtonClickToolStripMenuItem}); this.scriptToolStripMenuItem.Name = "scriptToolStripMenuItem"; this.scriptToolStripMenuItem.Size = new System.Drawing.Size(49, 20); this.scriptToolStripMenuItem.Text = "Script"; @@ -283,6 +287,36 @@ this.isTextInputToolStripMenuItem.Text = "Does active element accept text input"; this.isTextInputToolStripMenuItem.Click += new System.EventHandler(this.DoesActiveElementAcceptTextInputToolStripMenuItemClick); // + // doesElementWithIDExistToolStripMenuItem + // + 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); + // + // listenForButtonClickToolStripMenuItem + // + this.listenForButtonClickToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.goToDemoPageToolStripMenuItem, + this.injectJavascriptCodeToolStripMenuItem}); + this.listenForButtonClickToolStripMenuItem.Name = "listenForButtonClickToolStripMenuItem"; + this.listenForButtonClickToolStripMenuItem.Size = new System.Drawing.Size(271, 22); + this.listenForButtonClickToolStripMenuItem.Text = "Listen for button click"; + // + // goToDemoPageToolStripMenuItem + // + this.goToDemoPageToolStripMenuItem.Name = "goToDemoPageToolStripMenuItem"; + this.goToDemoPageToolStripMenuItem.Size = new System.Drawing.Size(186, 22); + this.goToDemoPageToolStripMenuItem.Text = "Go to demo page"; + this.goToDemoPageToolStripMenuItem.Click += new System.EventHandler(this.GoToDemoPageToolStripMenuItemClick); + // + // injectJavascriptCodeToolStripMenuItem + // + this.injectJavascriptCodeToolStripMenuItem.Name = "injectJavascriptCodeToolStripMenuItem"; + this.injectJavascriptCodeToolStripMenuItem.Size = new System.Drawing.Size(186, 22); + this.injectJavascriptCodeToolStripMenuItem.Text = "Inject Javascript code"; + this.injectJavascriptCodeToolStripMenuItem.Click += new System.EventHandler(this.InjectJavascriptCodeToolStripMenuItemClick); + // // browserTabControl // this.browserTabControl.Dock = System.Windows.Forms.DockStyle.Fill; @@ -292,13 +326,6 @@ this.browserTabControl.Size = new System.Drawing.Size(730, 466); this.browserTabControl.TabIndex = 2; // - // doesElementWithIDExistToolStripMenuItem - // - 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); - // // BrowserForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); @@ -349,6 +376,9 @@ private System.Windows.Forms.ToolStripMenuItem scriptToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem isTextInputToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem doesElementWithIDExistToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem listenForButtonClickToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem goToDemoPageToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem injectJavascriptCodeToolStripMenuItem; } } \ No newline at end of file diff --git a/CefSharp.WinForms.Example/BrowserForm.cs b/CefSharp.WinForms.Example/BrowserForm.cs index e2b60bc1f..45745cc18 100644 --- a/CefSharp.WinForms.Example/BrowserForm.cs +++ b/CefSharp.WinForms.Example/BrowserForm.cs @@ -368,5 +368,24 @@ namespace CefSharp.WinForms.Example }; dialog.Show(this); } + + private void GoToDemoPageToolStripMenuItemClick(object sender, EventArgs e) + { + var control = GetCurrentTabControl(); + if (control != null) + { + control.Browser.Load("custom://cefsharp/ScriptedMethodsTest.html"); + } + } + + private void InjectJavascriptCodeToolStripMenuItemClick(object sender, EventArgs e) + { + var control = GetCurrentTabControl(); + if (control != null) + { + var frame = control.Browser.GetFocusedFrame(); + ScriptedMethods.ListenForEvent("test-button", frame, "click"); + } + } } } diff --git a/CefSharp.WinForms.Example/BrowserTabUserControl.cs b/CefSharp.WinForms.Example/BrowserTabUserControl.cs index c58956cd3..f3d56a44e 100644 --- a/CefSharp.WinForms.Example/BrowserTabUserControl.cs +++ b/CefSharp.WinForms.Example/BrowserTabUserControl.cs @@ -8,6 +8,8 @@ using System.Runtime.InteropServices; using System.Windows.Forms; using CefSharp.WinForms.Example.Handlers; using CefSharp.WinForms.Internals; +using System.Collections.Generic; +using System.Linq; namespace CefSharp.WinForms.Example { @@ -47,6 +49,10 @@ namespace CefSharp.WinForms.Example browser.RegisterAsyncJsObject("boundAsync", new AsyncBoundObject()); browser.RenderProcessMessageHandler = new RenderProcessMessageHandler(); + var eventObject = new ScriptedMethodsBoundObject(); + eventObject.EventArrived += OnJavascriptEventArrived; + browser.RegisterJsObject("boundEvent", eventObject); + CefExample.RegisterTestResources(browser); var version = String.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion); @@ -86,6 +92,23 @@ namespace CefSharp.WinForms.Example this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = args.Address); } + private 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); + } + MessageBox.Show(message, "Javascript event arrived", MessageBoxButtons.OK, MessageBoxIcon.Information); + break; + } + } + private void SetCanGoBack(bool canGoBack) { this.InvokeOnUiThreadIfRequired(() => backButton.Enabled = canGoBack); diff --git a/CefSharp.WinForms.Example/InputBox.cs b/CefSharp.WinForms.Example/InputBox.cs index 6f006455f..1241818c8 100644 --- a/CefSharp.WinForms.Example/InputBox.cs +++ b/CefSharp.WinForms.Example/InputBox.cs @@ -1,11 +1,8 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +// Copyright © 2010-2015 The CefSharp Authors. All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. + +using System; using System.Windows.Forms; namespace CefSharp.WinForms.Example