【问题标题】:How can I programmatically open Microsoft.Maui.Controls.WebView DevTools?How can I programmatically open Microsoft.Maui.Controls.WebView DevTools?
【发布时间】:2022-12-02 07:56:55
【问题描述】:

MicrosoftMAUIuses aWebViewControl that wrapsMicrosoft.UI.Xaml.Controls.CoreWebView2.

How can I programmatically open the browser DevTools on windows and other supported platforms without causing exceptions on unsupported platforms?

【问题讨论】:

    标签: c# .net webview maui


    【解决方案1】:

    Since opening DevTools is a non-critical operation we can make a simple extension method that tries to find the method for launching dev tools without adding any references toMicrosoft.UI.Xaml. This way platforms that do not support DevTools will gracefully be ignored.

    Extension:

    public static class WebViewExtensions
    {
        /// <summary>
        /// Opens the DevTools if available.
        /// </summary>
        public static bool TryOpenDevToolsWindow(this WebView webView)
        { //Since this is a non-critical operation, use reflection instead of adding a permanent reference to
          //Microsoft.UI.Xaml.Controls namespace for CoreWebView2..
            if (webView != null)
            {
                var platfromView = webView.Handler.PlatformView;
                if (platfromView != null)
                {
                    var property = platfromView.GetType().GetProperty("CoreWebView2", BindingFlags.Instance | BindingFlags.Public);
                    if (property != null)
                    {
                        var coreWebView2 = property.GetValue(platfromView);
                        if (coreWebView2 != null)
                        {
                            var openMethod = coreWebView2.GetType().GetMethod("OpenDevToolsWindow");
                            if (openMethod != null)
                            {
                                dynamic r = openMethod.Invoke(coreWebView2, null);
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
    }
    

    Usage:

    private async void WebView_Navigated(object sender, WebNavigatedEventArgs e)
    {
        if (sender is WebView view)
        {
            view.TryOpenDevToolsWindow();
        }
    }
    

    Hope you find this useful!

    【讨论】:

      猜你喜欢
      • 2023-01-31
      • 2022-11-20
      • 2022-12-28
      • 2022-11-20
      • 2022-11-09
      • 2022-12-01
      • 2022-12-27
      • 2022-12-01
      • 2022-12-01
      相关资源
      最近更新 更多