Search code examples
c#winformswebview2

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?


Solution

  • 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;
    }