WPF WebView2中CoreWebView2_NewWindowRequested无法打开子窗口页面问题
解决WPF WebView2中NewWindowRequested事件无法加载子窗口网页的问题
我来帮你排查下这个问题,你的代码里有几个关键细节没处理对,导致子窗口无法正常显示目标网页:
问题分析
- 没有正确关联新窗口的CoreWebView2实例:WebView2的
NewWindowRequested事件需要通过e.NewWindow属性传递目标窗口的CoreWebView2实例,而不是手动创建WebView2后设置Source——这种手动设置的方式会跳过WebView2内置的新窗口加载逻辑,导致URL无法正确加载。 - URL存在多余空格:你的JS代码里
window.open("https://www.google.com ")的URL末尾多了个空格,可能会导致URL解析异常。 - 子窗口复用MainWindow可能引发冲突:如果你的
MainWindow本身已经包含WebView2控件,直接复用它作为子窗口可能会出现布局或控件初始化的冲突。
修正后的代码
1. 修改CoreWebView2_NewWindowRequested事件处理方法
private async void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e) { // 获取延迟对象,确保异步操作完成后再结束事件处理 var deferral = e.GetDeferral(); // 创建独立的子窗口(建议新建一个专门的空白Window,避免原MainWindow的布局冲突) var childWindow = new Window { Title = "Child Window", Width = 800, Height = 600 }; // 创建子窗口的WebView2控件 var childWebView = new WebView2(); childWindow.Content = childWebView; // 等待CoreWebView2初始化完成 await childWebView.EnsureCoreWebView2Async(); // *关键步骤*:将子窗口的CoreWebView2实例赋值给e.NewWindow,让WebView2自动处理URL加载 e.NewWindow = childWebView.CoreWebView2; // 标记事件已处理,阻止默认的弹窗行为 e.Handled = true; deferral.Complete(); childWindow.Show(); }
2. 修正JavaScript代码
去掉URL末尾的多余空格:
<script type="text/javascript"> function openPopup() { window.open("https://www.google.com"); } </script>
3. 确保主窗口WebView2正确初始化
记得在主窗口加载时完成WebView2的初始化并绑定事件:
private async void Window_Loaded(object sender, RoutedEventArgs e) { await MainWebView2Instance.EnsureCoreWebView2Async(); // 绑定NewWindowRequested事件 MainWebView2Instance.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested; }
为什么这样改?
- 通过
e.NewWindow关联子窗口的CoreWebView2是WebView2新窗口机制的标准用法,WebView2会自动把window.open请求的URL加载到这个关联的实例中,不需要手动设置Source。 - 使用独立的空白Window作为子窗口容器,避免原MainWindow的布局或控件带来的潜在冲突,如果需要自定义子窗口布局,可以新建一个专门的
ChildWindow.xaml文件。 - 修正URL的空格问题,避免解析错误导致网页无法加载。
内容的提问来源于stack exchange,提问作者DotNetSpartan
相关产品推荐
相关产品推荐

