[英]How can I programmatically open Microsoft.Maui.Controls.WebView DevTools?
Microsoft MAUI使用包装Microsoft.UI.Xaml.Controls.CoreWebView2的WebView控件。
如何以编程方式在 windows 和其他支持的平台上打开浏览器 DevTools 而不会在不受支持的平台上引起异常?
由于打开 DevTools 是一项非关键操作,我们可以创建一个简单的扩展方法,尝试找到启动开发工具的方法,而无需添加对Microsoft.UI.Xaml的任何引用。 这样,不支持 DevTools 的平台将被优雅地忽略。
延期:
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;
}
}
用法:
private async void WebView_Navigated(object sender, WebNavigatedEventArgs e)
{
if (sender is WebView view)
{
view.TryOpenDevToolsWindow();
}
}
希望你觉得这个有用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.