Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop webview2 from opening new browser window rather than inside the browser

Tags:

i want to know if there is anyway of stopping the webview2 component from opening a browser window in win forms

What is happening enter image description here

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#

like image 452
Foreverably Avatar asked Feb 02 '21 01:02

Foreverably


2 Answers

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:

Properties windows

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).

like image 91
Poul Bak Avatar answered Oct 06 '22 07:10

Poul Bak


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
like image 45
Code_Geass Avatar answered Oct 06 '22 08:10

Code_Geass