简体   繁体   中英

How to simulate a “open link on new window” on a C# WebBrowser?

I just found out that to simulate a click I can call element.InvokeMember("click"); where element is an HtmlElement . But what I actually need is to open the link in a new window, but not on the default browser but on another WebBrowser I would create in my program. Sometimes it works to just get the href attribute by calling element.GetAttribute("href"); and then just navigating to the returned URL, but some picky web pages won't work this way, I assume something to do with cookies and sessions.

System.Windows.Forms.WebBrowser is a very crippled control and one of its biggest problem - supporting of multi-tabbing. It doesn't support it at all.

I spent tons of time to try make it work properly but got no sufficient success, so recommend you to try 3rd party control instead.

Workaround: subscribe to click event of each <a> on page (or some of them you need) and create a new windows manually. For example, see how does it implemented in dotBrowser: 1 2

foreach (HtmlElement tag in webBrowser.Document.All)
{
    tag.Id = String.Empty;
    switch (tag.TagName.ToUpper())
    {
        case "A":
        {
            tag.MouseUp += new HtmlElementEventHandler(link_MouseUp);
            break;
        }
    }
}

private void link_MouseUp(object sender, HtmlElementEventArgs e)
{
    mshtml.HTMLAnchorElementClass a = (mshtml.HTMLAnchorElementClass)((HtmlElement)sender).DomElement;
    switch (e.MouseButtonsPressed)
    {
        case MouseButtons.Left:
        {
            // open new tab
            break;
        }
        case MouseButtons.Right:
        {
            // open context menu
            break;
        }
    }
}

Just handle the NewWindow2 event, create a form/tab that has a webbrowser on it, and use the webbrowser as the target of the new window request. Check http://www.codeproject.com/KB/cpp/ExtendedWebBrowser.aspx for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM