Search code examples
c#webview2

WebView2 - NavigateToString method returns "Operation Cancelled" error


The NavigateToString method returns an error for any html string provided as a parameter.

The event handler for NavigationCompleted returns Operation Canceled. Most likely the initialization is incorrect or incomplete but nut sure what.

Can you please help with a working C# sample so I can learn how to use webview2?

async void InitializeAsync()
{
        var env = await   Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(userDataFolder: cacheDirectory);
        await webView21.EnsureCoreWebView2Async(env);
        webView21.Dock = System.Windows.Forms.DockStyle.Right; //Fill
        webView21.NavigationStarting += EnsureHttps;
        webView21.NavigationCompleted += WebView21_NavigationCompleted;
  } 

...
...
webView21.CoreWebView2.NavigateToString("<html>HELLO!</html>"); //Fails
webView21.CoreWebView2.Navigate("https://www.google.com"); //Works

Solution

  • Since you can call Navigate("https://www.google.com") but not NavigateToString("<html>HELLO!</html>") the problem must be in the difference.

    And that is most likely caused by your EnsureHttps method.

    When you use NavigateToString it's NOT https! The url of the new page is about:blank!

    So you should check that in your EnsureHttps method and not redirect/change url if the url is about:blank.