I am using WebView2 inside my WPF Project.
At the moment, the behaviour is – if a webpage tries to open a new Window, there is a WebView2 Window opening outside my application.
What I would like to achieve is, that I can add a TabItem and open the requested Window within this TabItem.
I’ve tried using the CoreWebView2 NewWindowsRequested Event, this is my code:
private async void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
{
try
{
// Cast sender to CoreWebView2
CoreWebView2 coreWebView2Sender = (CoreWebView2)sender;
// Create a new TabItem
TabItem tab = new TabItem
{
Header = "Header"
};
// Add the new tab to the tabView
tabView.Items.Add(tab);
tabView.SelectedItem = tab;
// Create a new WebView2 element
WebView2 newWebView2 = new WebView2();
// Set the new WebView2 element as content of the tab
tab.Content = newWebView2;
// Use the environment of the sending WebView2 element
var environment = coreWebView2Sender.Environment;
// Initialize the new WebView2 element
await newWebView2.EnsureCoreWebView2Async(environment);
// Check if CoreWebView2 is initialized
if (newWebView2.CoreWebView2 != null)
{
// Assign the NewWindow handle to the new WebView2 element
e.NewWindow = newWebView2.CoreWebView2;
e.Handled = true;
}
else
{
// Handle the failure case if initialization fails
MessageBox.Show("Failed to initialize new WebView2 instance.");
e.Handled = false;
}
}
catch (Exception ex)
{
// Handle exceptions
MessageBox.Show($"An error occurred: {ex.Message}");
e.Handled = false;
}
}
However my main WebView2 is crashing with BrowserProcessExited.
If I just change the line e.NewWindow = newWebView2.CoreWebView2;
to newWebView2.Source = new Uri(e.Uri);
I get a new Tab, a new WebView2, and the requested Uri is displayed. So the WebView2 initialization should be fine. The strange thing is, that I also get the new WebView2 window with the content – so it seems that e.Handled
is not called, maybe not in time?
Moreover I think the prefered way is to use the NewWindow Element.
Has anybody an idea, why it’s not working if I set the NewWindow to the new CoreWebView2 I am creating?
Thanks!