0

I created a simple WPF client app in .net6.0 and incorporated WebView2 control. I deployed/copied this app to a different machine and also installed .NET6.0 runtime there. Upon running this app, I only see the main window and NO WebView2 initialized/created. Note this the same implementation is working on my dev machine.

public MainWindow()
{
    InitializeComponent();
    InitializeWebView2();
}

private async Task InitializeWebView2()
{
    //myPanel.Children.Add(webView2);
    //await webView2.EnsureCoreWebView2Async();
    ((Action)(async () =>
    {
        try
        {

            CoreWebView2Environment env = await CoreWebView2Environment.CreateAsync(null, "another_dir");
            WebView2 webview = new WebView2();

            /*
            webview.Source = new Uri("https://www.bing.com");
            */

            var result = webview.EnsureCoreWebView2Async(env).GetAwaiter();
            result.OnCompleted(() =>
            {
                try
                {
                    result.GetResult();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });


            myPanel.Children.Add(webview);
            webview.NavigateToString("https://google.com");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    })).Invoke();
}
sandy
  • 616
  • 2
  • 9
  • 20
  • seems like a duplicate https://stackoverflow.com/questions/65139090/how-can-i-initialize-the-webview2-in-wpf - WebView2 needs code behind initialization – Krzysztof Skowronek Oct 13 '22 at 12:13
  • Does this answer your question? [How can I initialize the WebView2 in WPF?](https://stackoverflow.com/questions/65139090/how-can-i-initialize-the-webview2-in-wpf) – Poul Bak Oct 14 '22 at 00:37
  • why are you creating new instance of WebView2 pragmatically when you already have this in xaml? – WitVault Oct 14 '22 at 08:28
  • No, i have removed it from XAML. – sandy Oct 14 '22 at 09:06

1 Answers1

1

EnsureCoreWebView2Async is supposed to be awaited before you set the Source:

private async Task InitializeWebView2()
{
    var webview = new WebView2();
    myPanel.Children.Add(webview);

    var env = await CoreWebView2Environment.CreateAsync(null, "another_dir");
    var result = await webview.EnsureCoreWebView2Async(env);
    webview.Source = new Uri("https://www.bing.com");
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Your statement is somewhat confusing maybe even incorrect. In fact implicit initialization can be done by setting the source and is the 2nd of 2 options to initialising Webview2core. https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.wpf.webview2?view=webview2-dotnet-1.0.1370.28 – darbid Oct 14 '22 at 20:41