Tiago Gomes
Tiago Gomes

Reputation: 160

How to prevent WebView2(Edge based) to open a new window

Inside Webview2 when I open a new tab, a new window outside WindowsForms is open. I want to prevent this window to Open, how can I do that?

Upvotes: 11

Views: 10318

Answers (3)

Ondrej Valenta
Ondrej Valenta

Reputation: 493

Just be careful about where you register the WebView.CoreWebView2.NewWindowRequested event..

I tried to use Browser.Initialized event in which handler I would register this event handler but that event is never raised.

I had to use Browser.CoreWebView2InitializationCompleted and now everything works just fine..

Upvotes: 2

Reza Aghaei
Reza Aghaei

Reputation: 125227

You can handle CoreWebView2.NewWindowRequested to decide about new window

  • To completely suppress the popup, set e.Handled = true;
  • To show the popup content in the same window, set e.NewWindow = (CoreWebView2)sender;
  • To open in another specific instance, set e.NewWindow to the other CoreWebView2 instance.

For example:

//using Microsoft.Web.WebView2.Core;
//using Microsoft.Web.WebView2.WinForms;

WebView2 webView21 = new WebView2();
private async void Form1_Load(object sender, EventArgs e)
{
    webView21.Dock = DockStyle.Fill;
    this.Controls.Add(webView21);
    webView21.Source = new Uri("Https://stackoverflow.com");
    await webView21.EnsureCoreWebView2Async();
    webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
}

private void CoreWebView2_NewWindowRequested(object sender,
    CoreWebView2NewWindowRequestedEventArgs e)
{
    e.NewWindow = (CoreWebView2)sender;
    //e.Handled = true;
}

Upvotes: 20

Code_Geass
Code_Geass

Reputation: 79

To complement @Reza 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

Upvotes: 2

Related Questions