在WebView2中初始化GuaranteeCoreWebView2Asyncnull时发生异常

问题描述

我正在将browser集成到我的软件中。当我继续打开新的浏览器选项卡时,它会起作用,但是一旦我关闭一个选项卡并尝试打开新的选项卡,它将在以下代码中产生异常。

public async Task InitCore()
{
    try
    {
        // Initialization.
        await webView.EnsureCoreWebView2Async(null);
        // This line gives exception if I close a tab and reopen as it gives exception in Initialization.
    }
    catch (Exception ex)
    {
         Enumerations.WritetoLog(Enumerations.LogType.Misc,"browser.InitCore " + ex.ToString());
    }
}

// Subscribing events.
private void AfterCoreReady(object sender,EventArgs e)
{
    label1.Visible = false;
    this.webView.CoreWebView2.ContentLoading += webView_ContentLoading;
    this.webView.CoreWebView2.NewWindowRequested += webView_NewWindowRequested;
}

关闭选项卡后重新初始化时发生以下异常:

CustomWebView2.OnEnter System.Runtime.InteropServices.COMException (0x8007139F): 
The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode,IntPtr errorInfo)
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
   at Microsoft.Web.WebView2.Core.CoreWebView2Environment.<CreateCoreWebView2ControllerAsync>d__17.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptiondispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Web.WebView2.WinForms.WebView2.<InitCoreWebView2Async>d__4.MoveNext()
--- End of stack trace from prevIoUs location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptiondispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at ProChart.Controls.browser.<InitCore>d__16.MoveNext() in
   browser.cs:line 98

解决方法

这就像每次导航到新页面时都在调用“Init”方法。

如果没有看到您的完整代码,我无法确定,但 WebView2 控件只应该初始化一次。

通常最好的方法是拨打您的等待电话

await webView.EnsureCoreWebView2Async(null);

在你的主应用程序中启动,例如你的主窗体在 windows 窗体或 WPF 应用程序中的构造函数。

但是,在较新的版本中,您无需等待一直使用的呼叫。

只需在构造函数中添加初始化代码,如下所示:

public FrmMainForm()
{
  InitializeComponent();

  webview.Height = 720;

  // Webview initialisation handler,called when control instantiated and ready
  webview.CoreWebView2InitializationCompleted += Webview_CoreWebView2InitializationCompleted;

}

在上面的示例中,我将控件嵌入到 Windows 窗体桌面应用程序中,因此我将其放入主窗体构造函数中。

一旦 webview2 控件准备好使用,“CoreWebView2InitializationCompleted”事件将被触发,然后您可以在该事件处理程序中初始化您的 webview 中的内容,例如 url 拦截、javascript 注入和 C# 类注入。

private void Webview_CoreWebView2InitializationCompleted(object sender,CoreWebView2InitializationCompletedEventArgs e)
{
  // Custom URL handler (All URLS starting "http://app/" are intercepted directly by the application
  webview.CoreWebView2.AddWebResourceRequestedFilter("http://app/*",CoreWebView2WebResourceContext.All);
  webview.CoreWebView2.WebResourceRequested += WebResourceRequested;

  // Load in our custom JS API files
  webview.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(JsLoader.LoadApi("BrowserOverrides.js"));
  // Show dev tools by default
  webview.CoreWebView2.OpenDevToolsWindow();

  // Other misc settings
  webview.CoreWebView2.Settings.UserAgent = DEFAULTUA;

}

我的 github 上有一些演示代码,其中包含有关如何使用所有这些功能的更多示例:

https://github.com/shawty/hbbtvbrowserEXPERIMENTAL

但是请注意,此代码使用旧版本的 webview2,我的代码中的某些内容在较新版本中的完成方式略有不同。