// Copyright © 2010-2017 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.Text; using System.Linq; using System.Threading.Tasks; using System.Globalization; using CefSharp.Internals; using System.IO; namespace CefSharp { public static class WebBrowserExtensions { private static Type[] numberTypes = new Type[] { typeof(int), typeof(uint), typeof(double), typeof(decimal), typeof(float), typeof(Int64), typeof(Int16) }; /// /// Returns the main (top-level) frame for the browser window. /// /// Frame public static IFrame GetMainFrame(this IWebBrowser webBrowser) { var browser = webBrowser.GetBrowser(); ThrowExceptionIfBrowserNull(browser); return browser.MainFrame; } /// /// Returns the focused frame for the browser window. /// /// Frame public static IFrame GetFocusedFrame(this IWebBrowser webBrowser) { var browser = webBrowser.GetBrowser(); ThrowExceptionIfBrowserNull(browser); return browser.FocusedFrame; } /// /// Execute Undo on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void Undo(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.Undo(); } } /// /// Execute Redo on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void Redo(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.Redo(); } } /// /// Execute Cut on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void Cut(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.Cut(); } } /// /// Execute Copy on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void Copy(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.Copy(); } } /// /// Execute Paste on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void Paste(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.Paste(); } } /// /// Execute Delete on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void Delete(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.Delete(); } } /// /// Execute SelectAll on the focused frame /// /// The ChromiumWebBrowser instance this method extends public static void SelectAll(this IWebBrowser browser) { using (var frame = browser.GetFocusedFrame()) { ThrowExceptionIfFrameNull(frame); frame.SelectAll(); } } /// /// Opens up a new program window (using the default text editor) where the source code of the currently displayed web /// page is shown. /// /// The ChromiumWebBrowser instance this method extends public static void ViewSource(this IWebBrowser browser) { using (var frame = browser.GetMainFrame()) { ThrowExceptionIfFrameNull(frame); frame.ViewSource(); } } /// /// Retrieve the main frame's HTML source using a . /// /// The ChromiumWebBrowser instance this method extends /// that when executed returns the frame source as a string public static Task GetSourceAsync(this IWebBrowser browser) { using (var frame = browser.GetMainFrame()) { ThrowExceptionIfFrameNull(frame); return frame.GetSourceAsync(); } } /// /// Retrieve the main frame's display text using a . /// /// The ChromiumWebBrowser instance this method extends /// that when executed returns the frame display text as a string. public static Task GetTextAsync(this IWebBrowser browser) { using (var frame = browser.GetMainFrame()) { ThrowExceptionIfFrameNull(frame); return frame.GetTextAsync(); } } /// /// Execute some Javascript code in the context of this WebBrowser. As the method name implies, the script will be /// executed asynchronously, and the method therefore returns before the script has actually been executed. /// This simple helper extension will encapsulate params in single quotes (unless int, uint, etc) /// /// The ChromiumWebBrowser instance this method extends /// The javascript method name to execute /// the arguments to be passed as params to the method public static void ExecuteScriptAsync(this IWebBrowser browser, string methodName, params object[] args) { var script = GetScript(methodName, args); browser.ExecuteScriptAsync(script); } /// /// Execute some Javascript code in the context of this WebBrowser. As the method name implies, the script will be /// executed asynchronously, and the method therefore returns before the script has actually been executed. /// /// The ChromiumWebBrowser instance this method extends /// The Javascript code that should be executed. public static void ExecuteScriptAsync(this IWebBrowser browser, string script) { if (browser.CanExecuteJavascriptInMainFrame == false) { throw new Exception("Unable to execute javascript at this time, scripts can only be executed within a V8Context." + "Use the IWebBrowser.CanExecuteJavascriptInMainFrame property to guard against this exception." + "See https://github.com/cefsharp/CefSharp/wiki/General-Usage#when-can-i-start-executing-javascript " + "for more details on when you can execute javascript."); } using (var frame = browser.GetMainFrame()) { ThrowExceptionIfFrameNull(frame); frame.ExecuteJavaScriptAsync(script); } } /// /// Load the string contents with the specified dummy url. Web security restrictions may not behave as expected. /// /// The ChromiumWebBrowser instance this method extends /// html string to load /// the url should have a standard scheme (for example, http scheme) or behaviors like link clicks public static void LoadString(this IWebBrowser browser, string html, string url) { using (var frame = browser.GetMainFrame()) { ThrowExceptionIfFrameNull(frame); frame.LoadStringForUrl(html, url); } } /// /// Registers and loads a that represents the HTML content. /// /// /// `Cef` Native `LoadHtml` is unpredictable and only works sometimes, this method wraps /// the provided HTML in a and loads the provided url using /// the method. /// Defaults to using for character encoding /// The url must start with a valid schema, other uri's such as about:blank are invalid /// A valid example looks like http://test/page /// /// The ChromiumWebBrowser instance this method extends /// The HTML content. /// The URL that will be treated as the address of the content. /// returns false if the Url was not successfully parsed into a Uri public static bool LoadHtml(this IWebBrowser browser, string html, string url) { return browser.LoadHtml(html, url, Encoding.UTF8); } /// /// Loads html as Data Uri /// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs for details /// If base64Encode is false then html will be Uri encoded /// /// The ChromiumWebBrowser instance this method extends /// Html to load as data uri. /// if true the html string will be base64 encoded using UTF8 encoding. public static void LoadHtml(this IWebBrowser browser, string html, bool base64Encode = false) { if(base64Encode) { var base64EncodedHtml = Convert.ToBase64String(Encoding.UTF8.GetBytes(html)); browser.Load("data:text/html;base64," + base64EncodedHtml); } else { var uriEncodedHtml = Uri.EscapeDataString(html); browser.Load("data:text/html," + uriEncodedHtml); } } /// /// Registers and loads a that represents the HTML content. /// /// /// `Cef` Native `LoadHtml` is unpredictable and only works sometimes, this method wraps /// the provided HTML in a and loads the provided url using /// the method. /// /// The ChromiumWebBrowser instance this method extends /// The HTML content. /// The URL that will be treated as the address of the content. /// Character Encoding /// returns false if the Url was not successfully parsed into a Uri public static bool LoadHtml(this IWebBrowser browser, string html, string url, Encoding encoding) { var handler = browser.ResourceHandlerFactory; if (handler == null) { throw new Exception("Implement IResourceHandlerFactory and assign to the ResourceHandlerFactory property to use this feature"); } var resourceHandler = handler as DefaultResourceHandlerFactory; if(resourceHandler == null) { throw new Exception("LoadHtml can only be used with the default IResourceHandlerFactory(DefaultResourceHandlerFactory) implementation"); } if (resourceHandler.RegisterHandler(url, ResourceHandler.FromString(html, encoding, true))) { browser.Load(url); return true; } return false; } /// /// Register a ResourceHandler. Can only be used when browser.ResourceHandlerFactory is an instance of DefaultResourceHandlerFactory /// /// The ChromiumWebBrowser instance this method extends /// the url of the resource to unregister /// Stream to be registered, the stream should not be shared with any other instances of DefaultResourceHandlerFactory /// the mimeType public static void RegisterResourceHandler(this IWebBrowser browser, string url, Stream stream, string mimeType = ResourceHandler.DefaultMimeType) { var handler = browser.ResourceHandlerFactory as DefaultResourceHandlerFactory; if (handler == null) { throw new Exception("RegisterResourceHandler can only be used with the default IResourceHandlerFactory(DefaultResourceHandlerFactory) implementation"); } handler.RegisterHandler(url, ResourceHandler.FromStream(stream, mimeType)); } /// /// Unregister a ResourceHandler. Can only be used when browser.ResourceHandlerFactory is an instance of DefaultResourceHandlerFactory /// /// The ChromiumWebBrowser instance this method extends /// the url of the resource to unregister public static void UnRegisterResourceHandler(this IWebBrowser browser, string url) { var handler = browser.ResourceHandlerFactory as DefaultResourceHandlerFactory; if (handler == null) { throw new Exception("UnRegisterResourceHandler can only be used with the default IResourceHandlerFactory(DefaultResourceHandlerFactory) implementation"); } handler.UnregisterHandler(url); } /// /// Stops loading the current page. /// public static void Stop(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.StopLoad(); } /// /// Navigates back, must check before calling this method. /// public static void Back(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.GoBack(); } /// /// Navigates forward, must check before calling this method. /// public static void Forward(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.GoForward(); } /// /// Reloads the page being displayed. This method will use data from the browser's cache, if available. /// public static void Reload(this IWebBrowser browser) { browser.Reload(false); } /// /// Reloads the page being displayed, optionally ignoring the cache (which means the whole page including all .css, .js /// etc. resources will be re-fetched). /// /// The ChromiumWebBrowser instance this method extends /// true A reload is performed ignoring browser cache; false A reload is /// performed using files from the browser cache, if available. public static void Reload(this IWebBrowser browser, bool ignoreCache) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.Reload(ignoreCache); } /// /// Asynchronously gets the current Zoom Level. /// public static Task GetZoomLevelAsync(this IBrowser cefBrowser) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); return host.GetZoomLevelAsync(); } /// /// Asynchronously gets the current Zoom Level. /// public static Task GetZoomLevelAsync(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); return cefBrowser.GetZoomLevelAsync(); } /// /// Change the ZoomLevel to the specified value. Can be set to 0.0 to clear the zoom level. /// /// /// If called on the CEF UI thread the change will be applied immediately. /// Otherwise, the change will be applied asynchronously on the CEF UI thread. /// The CEF UI thread is different to the WPF/WinForms UI Thread /// /// The ChromiumWebBrowser instance this method extends /// zoom level public static void SetZoomLevel(this IBrowser cefBrowser, double zoomLevel) { ThrowExceptionIfBrowserNull(cefBrowser); var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.SetZoomLevel(zoomLevel); } /// /// Change the ZoomLevel to the specified value. Can be set to 0.0 to clear the zoom level. /// /// /// If called on the CEF UI thread the change will be applied immediately. /// Otherwise, the change will be applied asynchronously on the CEF UI thread. /// The CEF UI thread is different to the WPF/WinForms UI Thread /// /// The ChromiumWebBrowser instance this method extends /// zoom level public static void SetZoomLevel(this IWebBrowser browser, double zoomLevel) { var cefBrowser = browser.GetBrowser(); cefBrowser.SetZoomLevel(zoomLevel); } /// /// Search for text within the current page. /// /// The ChromiumWebBrowser instance this method extends /// Can be used in can conjunction with searchText to have multiple /// searches running simultaneously. /// search text /// indicates whether to search forward or backward within the page. /// indicates whether the search should be case-sensitive. /// indicates whether this is the first request or a follow-up. public static void Find(this IBrowser cefBrowser, int identifier, string searchText, bool forward, bool matchCase, bool findNext) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.Find(identifier, searchText, forward, matchCase, findNext); } /// /// Search for text within the current page. /// /// The ChromiumWebBrowser instance this method extends /// Can be used in can conjunction with searchText to have multiple /// searches running simultaneously. /// search text /// indicates whether to search forward or backward within the page. /// indicates whether the search should be case-sensitive. /// indicates whether this is the first request or a follow-up. public static void Find(this IWebBrowser browser, int identifier, string searchText, bool forward, bool matchCase, bool findNext) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.Find(identifier, searchText, forward, matchCase, findNext); } /// /// Cancel all searches that are currently going on. /// /// The ChromiumWebBrowser instance this method extends /// clear the current search selection public static void StopFinding(this IBrowser cefBrowser, bool clearSelection) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.StopFinding(clearSelection); } /// /// Cancel all searches that are currently going on. /// /// The ChromiumWebBrowser instance this method extends /// clear the current search selection public static void StopFinding(this IWebBrowser browser, bool clearSelection) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.StopFinding(clearSelection); } /// /// Opens a Print Dialog which if used (can be user cancelled) will print the browser contents. /// /// The ChromiumWebBrowser instance this method extends public static void Print(this IBrowser cefBrowser) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.Print(); } /// /// Asynchronously prints the current browser contents to the PDF file specified. /// The caller is responsible for deleting the file when done. /// /// The object this method extends. /// Output file location. /// Print Settings. /// A task that represents the asynchronous print operation. /// The result is true on success or false on failure to generate the Pdf. public static Task PrintToPdfAsync(this IBrowser cefBrowser, string path, PdfPrintSettings settings = null) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); var callback = new TaskPrintToPdfCallback(); host.PrintToPdf(path, settings, callback); return callback.Task; } /// /// Opens a Print Dialog which if used (can be user cancelled) will print the browser contents. /// /// The ChromiumWebBrowser instance this method extends public static void Print(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.Print(); } /// /// Asynchronously prints the current browser contents to the PDF file specified. /// The caller is responsible for deleting the file when done. /// /// The ChromiumWebBrowser instance this method extends /// Output file location. /// Print Settings. /// A task that represents the asynchronous print operation. /// The result is true on success or false on failure to generate the Pdf. public static Task PrintToPdfAsync(this IWebBrowser browser, string path, PdfPrintSettings settings = null) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); return cefBrowser.PrintToPdfAsync(path, settings); } /// /// Open developer tools in its own window. /// /// The ChromiumWebBrowser instance this method extends public static void ShowDevTools(this IBrowser cefBrowser) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.ShowDevTools(); } /// /// Open developer tools in its own window. /// /// The ChromiumWebBrowser instance this method extends public static void ShowDevTools(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.ShowDevTools(); } /// /// Explicitly close the developer tools window if one exists for this browser instance. /// /// The ChromiumWebBrowser instance this method extends public static void CloseDevTools(this IBrowser cefBrowser) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.CloseDevTools(); } /// /// Explicitly close the developer tools window if one exists for this browser instance. /// /// The ChromiumWebBrowser instance this method extends public static void CloseDevTools(this IWebBrowser browser) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.CloseDevTools(); } /// /// If a misspelled word is currently selected in an editable node calling /// this method will replace it with the specified word. /// /// The ChromiumWebBrowser instance this method extends /// The new word that will replace the currently selected word. public static void ReplaceMisspelling(this IBrowser cefBrowser, string word) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.ReplaceMisspelling(word); } /// /// If a misspelled word is currently selected in an editable node calling /// this method will replace it with the specified word. /// /// The ChromiumWebBrowser instance this method extends /// The new word that will replace the currently selected word. public static void ReplaceMisspelling(this IWebBrowser browser, string word) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.ReplaceMisspelling(word); } /// /// Add the specified word to the spelling dictionary. /// /// The ChromiumWebBrowser instance this method extends /// The new word that will be added to the dictionary. public static void AddWordToDictionary(this IBrowser cefBrowser, string word) { var host = cefBrowser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.AddWordToDictionary(word); } /// /// Add the specified word to the spelling dictionary. /// /// The ChromiumWebBrowser instance this method extends /// The new word that will be added to the dictionary. public static void AddWordToDictionary(this IWebBrowser browser, string word) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.AddWordToDictionary(word); } public static void SendMouseWheelEvent(this IWebBrowser browser, int x, int y, int deltaX, int deltaY, CefEventFlags modifiers) { var cefBrowser = browser.GetBrowser(); ThrowExceptionIfBrowserNull(cefBrowser); cefBrowser.SendMouseWheelEvent(x, y, deltaX, deltaY, modifiers); } public static void SendMouseWheelEvent(this IBrowser browser, int x, int y, int deltaX, int deltaY, CefEventFlags modifiers) { var host = browser.GetHost(); ThrowExceptionIfBrowserHostNull(host); host.SendMouseWheelEvent(new MouseEvent(x, y, modifiers), deltaX, deltaY); } public static void SendMouseWheelEvent(this IBrowserHost host, int x, int y, int deltaX, int deltaY, CefEventFlags modifiers) { ThrowExceptionIfBrowserHostNull(host); host.SendMouseWheelEvent(new MouseEvent(x, y, modifiers), deltaX, deltaY); } public static void SendMouseClickEvent(this IBrowserHost host, int x, int y, MouseButtonType mouseButtonType, bool mouseUp, int clickCount, CefEventFlags modifiers) { ThrowExceptionIfBrowserHostNull(host); host.SendMouseClickEvent(new MouseEvent(x, y, modifiers), mouseButtonType, mouseUp, clickCount); } public static void SendMouseMoveEvent(this IBrowserHost host, int x, int y, bool mouseLeave, CefEventFlags modifiers) { ThrowExceptionIfBrowserHostNull(host); host.SendMouseMoveEvent(new MouseEvent(x, y, modifiers), mouseLeave); } public static Task EvaluateScriptAsync(this IWebBrowser browser, string script, TimeSpan? timeout = null) { if (timeout.HasValue && timeout.Value.TotalMilliseconds > UInt32.MaxValue) { throw new ArgumentOutOfRangeException("timeout", "Timeout greater than Maximum allowable value of " + UInt32.MaxValue); } if(browser.CanExecuteJavascriptInMainFrame == false) { throw new Exception("Unable to execute javascript at this time, scripts can only be executed within a V8Context." + "Use the IWebBrowser.CanExecuteJavascriptInMainFrame property to guard against this exception." + "See https://github.com/cefsharp/CefSharp/wiki/General-Usage#when-can-i-start-executing-javascript " + "for more details on when you can execute javascript."); } using (var frame = browser.GetMainFrame()) { ThrowExceptionIfFrameNull(frame); return frame.EvaluateScriptAsync(script, timeout: timeout); } } /// /// Evaluate some Javascript code in the context of this WebBrowser. The script will be executed asynchronously and the /// method returns a Task encapsulating the response from the Javascript /// This simple helper extension will encapsulate params in single quotes (unless int, uint, etc) /// /// The ChromiumWebBrowser instance this method extends /// The javascript method name to execute /// the arguments to be passed as params to the method /// that can be awaited to perform the script execution public static Task EvaluateScriptAsync(this IWebBrowser browser, string methodName, params object[] args) { return browser.EvaluateScriptAsync(null, methodName, args); } /// /// Evaluate some Javascript code in the context of this WebBrowser using the specified timeout. The script will be executed asynchronously and the /// method returns a Task encapsulating the response from the Javascript /// This simple helper extension will encapsulate params in single quotes (unless int, uint, etc) /// /// The ChromiumWebBrowser instance this method extends /// The timeout after which the Javascript code execution should be aborted. /// The javascript method name to execute /// the arguments to be passed as params to the method /// that can be awaited to perform the script execution public static Task EvaluateScriptAsync(this IWebBrowser browser, TimeSpan? timeout, string methodName, params object[] args) { var script = GetScript(methodName, args); return browser.EvaluateScriptAsync(script, timeout); } public static void SetAsPopup(this IWebBrowser browser) { var internalBrowser = (IWebBrowserInternal)browser; internalBrowser.HasParent = true; } public static void ThrowExceptionIfBrowserNotInitialized(this IWebBrowser browser) { if (!browser.IsBrowserInitialized) { throw new Exception("Browser is not yet initialized. Use the IsBrowserInitializedChanged event and check " + "the IsBrowserInitialized property to determine when the browser has been intialized."); } } /// /// Transforms the methodName and arguments into valid Javascript code. Will encapsulate params in single quotes (unless int, uint, etc) /// /// The javascript method name to execute /// the arguments to be passed as params to the method /// The Javascript code private static string GetScript(string methodName, object[] args) { var stringBuilder = new StringBuilder(); stringBuilder.Append(methodName); stringBuilder.Append("("); if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { var obj = args[i]; if (obj == null) { stringBuilder.Append("null"); } else if (numberTypes.Contains(obj.GetType())) { stringBuilder.Append(Convert.ToString(args[i], CultureInfo.InvariantCulture)); } else if (obj is bool) { stringBuilder.Append(args[i].ToString().ToLowerInvariant()); } else { stringBuilder.Append("'"); stringBuilder.Append(args[i].ToString().Replace("'", "\\'")); stringBuilder.Append("'"); } stringBuilder.Append(", "); } //Remove the trailing comma stringBuilder.Remove(stringBuilder.Length - 2, 2); } stringBuilder.Append(");"); return stringBuilder.ToString(); } private static void ThrowExceptionIfFrameNull(IFrame frame) { if (frame == null) { throw new Exception("IFrame instance is null. Browser has likely not finished initializing or is in the process of disposing."); } } private static void ThrowExceptionIfBrowserNull(IBrowser browser) { if (browser == null) { throw new Exception("IBrowser instance is null. Browser has likely not finished initializing or is in the process of disposing."); } } private static void ThrowExceptionIfBrowserHostNull(IBrowserHost browserHost) { if (browserHost == null) { throw new Exception("IBrowserHost instance is null. Browser has likely not finished initializing or is in the process of disposing."); } } } }