i want to know if there is anyway of stopping the webview2 component from opening a browser window in win forms
What is happening
i looked everywhere but could not find one, i did find one though, but it used XAML/UWP
one page used xaml but the code wont work because its XAML and im using c#
To stop the link from opening in a new window, you subscribe to the CoreWebView2_NewWindowRequested
as you have found out.
To do that, the easiest way is to subscribe to the CoreWebView2InitializationCompleted
first.
In properties window for the WebView2
control, double click CoreWebView2InitializationCompleted
- that will auto generate the eventhandler:
Now you add the CoreWebView2_NewWindowRequested
eventhandler and set e.NewWindow
to the current CoreWebView2
.
Here's the code (assuming your WebView2
control is called webView21
):
private void WebView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
}
private void CoreWebView2_NewWindowRequested(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NewWindowRequestedEventArgs e)
{
e.NewWindow = webView21.CoreWebView2;
}
Now the link opens in the same window (your WebView2
control).
To complement @Poul Bak answer I was having this exact problem in VB.Net but all the answers were for C# so im going to post it in here if anyone else needs it.
First make sure to import this:
Imports Microsoft.Web.WebView2.Core
Imports Microsoft.Web.WebView2.WinForms
And then add this 2 events just replace wVBrowser with your Webview2 control name.
Private Sub wVBrowser_CoreWebView2InitializationCompleted(sender As Object, e As CoreWebView2InitializationCompletedEventArgs) Handles wVBrowser.CoreWebView2InitializationCompleted
AddHandler wVBrowser.CoreWebView2.NewWindowRequested, AddressOf CoreWebView2_NewWindowRequested
End Sub
Private Sub CoreWebView2_NewWindowRequested(ByVal sender As Object, ByVal e As Microsoft.Web.WebView2.Core.CoreWebView2NewWindowRequestedEventArgs)
e.Handled = True
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With