how to detect and open link in new tab/window/winform in DotNetBrowser

Solution 1:

CreatePopupHandler handler is invoked when the engine wants to know whether pop-up can be created or not. Basically, you can use it either to allow or suppress pop-ups creation in general.

If the CreatePopupHandler handler allows creating a pop-up, the OpenPopupHandler handler is invoked. In this handler, you can access the created pop-up and display it if necessary.

When you initialize a WinForms BrowserView, it automatically configures the given IBrowser instance with the default implementation of the CreatePopupHandler and OpenPopupHandler handlers.

In this case, there are two scenarios when links are opened in a new window (pop-up):

  1. The window.open() JavaScript function:
window.open("https://www.google.com", "_blank", 
    "resizable=yes, top=500, left=500, width=400, height=400");
  1. A link with target attribute:
<a href="https://www.google.com" target="_blank">Open Google</a>

To load any URL in a separate window or tab on a navigation attempt (e.g. clicking a link), you will need to intercept all or required navigation requests using StartNavigationHandler. In the handler implementation, you need to create a new window or tab with browser, load this URL into it, and cancel its loading in the original browser. For example:

browser.Navigation.StartNavigationHandler =
    new Handler<StartNavigationParameters, StartNavigationResponse>((p) =>
    {
        // Intercept all navigation requests to the URLs that start 
        // with "https://dotnetbrowser" and load them into a new form
        if (p.Url.StartsWith("https://dotnetbrowser"))
        {
            BeginInvoke((Action)(() => 
            {
                LoadNewWindow(p.Url);
            }));
            return StartNavigationResponse.Ignore();
        }
        return StartNavigationResponse.Start();
    });
browser?.Navigation.LoadUrl("https://teamdev.com/dotnetbrowser");

The LoadNewWindow implementation:

private void LoadNewWindow(string url)
{
    var browser1 = engine.CreateBrowser();

    BrowserView browserView = new BrowserView
    {
        Dock = DockStyle.Fill
    };

    browserView.InitializeFrom(browser1);

    Form form = new Form();

    form.Width = 800;
    form.Height = 600;

    form.Closed += delegate
    {
        form.Controls.Clear();

        if (!browser1.IsDisposed)
        {
            browser1.Dispose();
        }
    };

    form.Controls.Add(browserView);
    form.Show();

    browser1.Navigation.LoadUrl(url);
}