Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Tiago Gomes Avatar asked Jan 25 '23 11:01

Tiago Gomes


1 Answers

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;
}
like image 96
Reza Aghaei Avatar answered Jan 27 '23 01:01

Reza Aghaei