From 5691669df3a344a14bb5e693b7d6cf331898efbe Mon Sep 17 00:00:00 2001 From: Rich McNeary Date: Mon, 14 Dec 2015 14:54:04 -0500 Subject: [PATCH] Initial script examples. --- CefSharp.Example/CefSharp.Example.csproj | 1 + CefSharp.Example/ScriptedMethods.cs | 83 ++++++++++++ .../BrowserForm.Designer.cs | 32 ++++- CefSharp.WinForms.Example/BrowserForm.cs | 69 ++++++++++ .../CefSharp.WinForms.Example.csproj | 11 ++ .../InputBox.Designer.cs | 124 ++++++++++++++++++ CefSharp.WinForms.Example/InputBox.cs | 54 ++++++++ CefSharp.WinForms.Example/InputBox.resx | 120 +++++++++++++++++ 8 files changed, 493 insertions(+), 1 deletion(-) create mode 100644 CefSharp.Example/ScriptedMethods.cs create mode 100644 CefSharp.WinForms.Example/InputBox.Designer.cs create mode 100644 CefSharp.WinForms.Example/InputBox.cs create mode 100644 CefSharp.WinForms.Example/InputBox.resx diff --git a/CefSharp.Example/CefSharp.Example.csproj b/CefSharp.Example/CefSharp.Example.csproj index c168ee10b..69d13154a 100644 --- a/CefSharp.Example/CefSharp.Example.csproj +++ b/CefSharp.Example/CefSharp.Example.csproj @@ -78,6 +78,7 @@ + diff --git a/CefSharp.Example/ScriptedMethods.cs b/CefSharp.Example/ScriptedMethods.cs new file mode 100644 index 000000000..a9003476d --- /dev/null +++ b/CefSharp.Example/ScriptedMethods.cs @@ -0,0 +1,83 @@ +// 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.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace CefSharp.Example +{ + public class ScriptedMethods + { + public static async Task ActiveElementAcceptsTextInput(IFrame frame) + { + if (frame == null) + { + throw new ArgumentException("An IFrame instance is required.", "frame"); + } + + // 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;" + + "})();"; + + var response = await frame.EvaluateScriptAsync(script); + if (!response.Success) + { + throw new Exception(response.Message); + } + + return (bool)response.Result; + } + + public static async Task ElementWithIdExists(string id, IFrame frame) + { + if (frame == null) + { + throw new ArgumentException("An IFrame instance is required.", "frame"); + } + + var script = + "(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 + // it's probably safer to include tokens that can be replaced via + // regex. + script = Regex.Replace(script, "##ID##", id); + + var response = await frame.EvaluateScriptAsync(script); + if (!response.Success) + { + throw new Exception(response.Message); + } + + return (bool)response.Result; + } + } +} diff --git a/CefSharp.WinForms.Example/BrowserForm.Designer.cs b/CefSharp.WinForms.Example/BrowserForm.Designer.cs index df048ffa9..49bfe0168 100644 --- a/CefSharp.WinForms.Example/BrowserForm.Designer.cs +++ b/CefSharp.WinForms.Example/BrowserForm.Designer.cs @@ -55,7 +55,10 @@ this.zoomInToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.zoomOutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); 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.menuStrip1.SuspendLayout(); this.SuspendLayout(); // @@ -64,7 +67,8 @@ this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, - this.zoomLevelToolStripMenuItem}); + this.zoomLevelToolStripMenuItem, + this.scriptToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(730, 24); @@ -263,6 +267,22 @@ this.currentZoomLevelToolStripMenuItem.Text = "Current Zoom Level"; this.currentZoomLevelToolStripMenuItem.Click += new System.EventHandler(this.CurrentZoomLevelToolStripMenuItemClick); // + // scriptToolStripMenuItem + // + this.scriptToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.isTextInputToolStripMenuItem, + this.doesElementWithIDExistToolStripMenuItem}); + this.scriptToolStripMenuItem.Name = "scriptToolStripMenuItem"; + this.scriptToolStripMenuItem.Size = new System.Drawing.Size(49, 20); + this.scriptToolStripMenuItem.Text = "Script"; + // + // isTextInputToolStripMenuItem + // + this.isTextInputToolStripMenuItem.Name = "isTextInputToolStripMenuItem"; + this.isTextInputToolStripMenuItem.Size = new System.Drawing.Size(271, 22); + this.isTextInputToolStripMenuItem.Text = "Does active element accept text input"; + this.isTextInputToolStripMenuItem.Click += new System.EventHandler(this.DoesActiveElementAcceptTextInputToolStripMenuItemClick); + // // browserTabControl // this.browserTabControl.Dock = System.Windows.Forms.DockStyle.Fill; @@ -272,6 +292,13 @@ 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); @@ -319,6 +346,9 @@ private System.Windows.Forms.ToolStripMenuItem zoomInToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem zoomOutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem currentZoomLevelToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem scriptToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem isTextInputToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem doesElementWithIDExistToolStripMenuItem; } } \ No newline at end of file diff --git a/CefSharp.WinForms.Example/BrowserForm.cs b/CefSharp.WinForms.Example/BrowserForm.cs index 511997fe9..e2b60bc1f 100644 --- a/CefSharp.WinForms.Example/BrowserForm.cs +++ b/CefSharp.WinForms.Example/BrowserForm.cs @@ -299,5 +299,74 @@ namespace CefSharp.WinForms.Example }, TaskContinuationOptions.HideScheduler); } } + + private void DoesActiveElementAcceptTextInputToolStripMenuItemClick(object sender, EventArgs e) + { + var control = GetCurrentTabControl(); + if (control != null) + { + var frame = control.Browser.GetFocusedFrame(); + ScriptedMethods.ActiveElementAcceptsTextInput(frame) + .ContinueWith(task => + { + 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 "); + } + + MessageBox.Show(message, "Does active element accept text input", MessageBoxButtons.OK, icon); + }); + } + } + + 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(); + } + + dialog.Result = message; + })); + }); + } + }; + dialog.Show(this); + } } } diff --git a/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj b/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj index 948954316..911daf08a 100644 --- a/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj +++ b/CefSharp.WinForms.Example/CefSharp.WinForms.Example.csproj @@ -55,8 +55,10 @@ 3.5 + + @@ -83,6 +85,12 @@ + + Form + + + InputBox.cs + Form @@ -117,6 +125,9 @@ BrowserTabUserControl.cs Designer + + InputBox.cs + SimpleBrowserForm.cs diff --git a/CefSharp.WinForms.Example/InputBox.Designer.cs b/CefSharp.WinForms.Example/InputBox.Designer.cs new file mode 100644 index 000000000..46a349fed --- /dev/null +++ b/CefSharp.WinForms.Example/InputBox.Designer.cs @@ -0,0 +1,124 @@ +namespace CefSharp.WinForms.Example +{ + partial class InputBox + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this._instructions = new System.Windows.Forms.Label(); + this._value = new System.Windows.Forms.TextBox(); + this._evaluate = new System.Windows.Forms.Button(); + this._result = new System.Windows.Forms.TextBox(); + this._resultLabel = new System.Windows.Forms.Label(); + this._close = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // _instructions + // + this._instructions.AutoSize = true; + this._instructions.Location = new System.Drawing.Point(12, 19); + this._instructions.Name = "_instructions"; + this._instructions.Size = new System.Drawing.Size(104, 13); + this._instructions.TabIndex = 0; + this._instructions.Text = "Enter an element ID."; + // + // _value + // + this._value.Location = new System.Drawing.Point(12, 35); + this._value.Name = "_value"; + this._value.Size = new System.Drawing.Size(411, 20); + this._value.TabIndex = 1; + // + // _evaluate + // + this._evaluate.Location = new System.Drawing.Point(429, 33); + this._evaluate.Name = "_evaluate"; + this._evaluate.Size = new System.Drawing.Size(92, 23); + this._evaluate.TabIndex = 2; + this._evaluate.Text = "Evaluate"; + this._evaluate.UseVisualStyleBackColor = true; + // + // _result + // + this._result.Location = new System.Drawing.Point(58, 64); + this._result.Name = "_result"; + this._result.ReadOnly = true; + this._result.Size = new System.Drawing.Size(365, 20); + this._result.TabIndex = 3; + // + // _resultLabel + // + this._resultLabel.AutoSize = true; + this._resultLabel.Location = new System.Drawing.Point(12, 67); + this._resultLabel.Name = "_resultLabel"; + this._resultLabel.Size = new System.Drawing.Size(40, 13); + this._resultLabel.TabIndex = 4; + this._resultLabel.Text = "Result:"; + this._resultLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; + // + // _close + // + this._close.Location = new System.Drawing.Point(429, 130); + this._close.Name = "_close"; + this._close.Size = new System.Drawing.Size(92, 23); + this._close.TabIndex = 5; + this._close.Text = "Close"; + this._close.UseVisualStyleBackColor = true; + this._close.Click += new System.EventHandler(this._close_Click); + // + // InputBox + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(533, 165); + this.Controls.Add(this._close); + this.Controls.Add(this._resultLabel); + this.Controls.Add(this._result); + this.Controls.Add(this._evaluate); + this.Controls.Add(this._value); + this.Controls.Add(this._instructions); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "InputBox"; + this.ShowInTaskbar = false; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Evaluate script"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label _instructions; + private System.Windows.Forms.TextBox _value; + private System.Windows.Forms.Button _evaluate; + private System.Windows.Forms.TextBox _result; + private System.Windows.Forms.Label _resultLabel; + private System.Windows.Forms.Button _close; + } +} \ No newline at end of file diff --git a/CefSharp.WinForms.Example/InputBox.cs b/CefSharp.WinForms.Example/InputBox.cs new file mode 100644 index 000000000..6f006455f --- /dev/null +++ b/CefSharp.WinForms.Example/InputBox.cs @@ -0,0 +1,54 @@ +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; +using System.Windows.Forms; + +namespace CefSharp.WinForms.Example +{ + public partial class InputBox : Form + { + public InputBox() + { + InitializeComponent(); + } + + public event EventHandler OnEvaluate + { + add { _evaluate.Click += value; } + remove { _evaluate.Click -= value; } + } + + public string Instructions + { + get { return _instructions.Text; } + set { _instructions.Text = value; } + } + + public string Result + { + get { return _result.Text; } + set { _result.Text = value; } + } + + public string Title + { + set { Text = "Evaluate script - " + value; } + } + + public string Value + { + get { return _value.Text; } + set { _value.Text = value; } + } + + private void _close_Click(object sender, EventArgs e) + { + Close(); + } + } +} diff --git a/CefSharp.WinForms.Example/InputBox.resx b/CefSharp.WinForms.Example/InputBox.resx new file mode 100644 index 000000000..1af7de150 --- /dev/null +++ b/CefSharp.WinForms.Example/InputBox.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file