From 3cc3e642e9f84f20a5dabb12d23d6c332f063804 Mon Sep 17 00:00:00 2001 From: Alex Maitland Date: Thu, 11 Nov 2021 12:47:16 +1000 Subject: [PATCH] WinForms - Implement ChromiumWebBrowser.LoadError --- .../BrowserForm.cs | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/CefSharp.MinimalExample.WinForms/BrowserForm.cs b/CefSharp.MinimalExample.WinForms/BrowserForm.cs index f68b90e..b1a17c8 100644 --- a/CefSharp.MinimalExample.WinForms/BrowserForm.cs +++ b/CefSharp.MinimalExample.WinForms/BrowserForm.cs @@ -35,6 +35,7 @@ namespace CefSharp.MinimalExample.WinForms browser.StatusMessage += OnBrowserStatusMessage; browser.TitleChanged += OnBrowserTitleChanged; browser.AddressChanged += OnBrowserAddressChanged; + browser.LoadError += OnBrowserLoadError; var version = string.Format("Chromium: {0}, CEF: {1}, CefSharp: {2}", Cef.ChromiumVersion, Cef.CefVersion, Cef.CefSharpVersion); @@ -53,6 +54,34 @@ namespace CefSharp.MinimalExample.WinForms DisplayOutput(string.Format("{0}, {1}", version, environment)); } + private async void OnBrowserLoadError(object sender, LoadErrorEventArgs e) + { + //Actions that trigger a download will raise an aborted error. + //Aborted is generally safe to ignore + if (e.ErrorCode == CefErrorCode.Aborted) + { + return; + } + + //using LoadHtml/LoadUrl creates an additional history entry that + //prevents the back button from working correctly. + //Use Devools Page.SetDocumentContent to change the content + using (var client = browser.GetDevToolsClient()) + { + var response = await client.Page.GetFrameTreeAsync(); + var frames = response.FrameTree; + var mainFrame = frames.Frame; + + var errorHtml = string.Format("

Failed to load URL {0} with error {1} ({2}).

", + e.FailedUrl, e.ErrorText, e.ErrorCode); + + _ = client.Page.SetDocumentContentAsync(mainFrame.Id, errorHtml); + + //AddressChanged isn't called for failed Urls so we need to manually update the Url TextBox + this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = e.FailedUrl); + } + } + private void OnIsBrowserInitializedChanged(object sender, EventArgs e) { var b = ((ChromiumWebBrowser)sender);