Open new web page in new tab in WebBrowser control

后端 未结 3 1698
独厮守ぢ
独厮守ぢ 2020-12-07 04:01

I\'m using WebBrowser control in my c# application, and I want to open web pages in it.
It\'s completely done.

My problem:

Any link in the

3条回答
  •  有刺的猬
    2020-12-07 04:15

    There is two ways you can work around on this. Both methods begin with capturing the click event and then detecting whether an "a" element is clicked.

    Method 1 simply gets the URL, cancel the click, and have the open a new tab. Opening a new tab may be achieved by simply instantiating a new WebBrowser control at the right place.

    Method 2 simply removes the _blank from the target so that the page opens on the current browser rather than spawning another browser window.

    private void Go(string url)
    {
        webBrowser1.Navigate(url);
        webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
    }
    
    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.Click += new HtmlElementEventHandler(Document_Click);
    }
    
    void Document_Click(object sender, HtmlElementEventArgs e)
    {
        HtmlElement ele = webBrowser1.Document.GetElementFromPoint(e.MousePosition);
        while (ele != null)
        {
            if (ele.TagName.ToLower() == "a")
            {
                // METHOD-1
                // Use the url to open a new tab
                string url = ele.GetAttribute("href");
                // TODO: open the new tab
                e.ReturnValue = false;
    
                // METHOD-2
                // Use this to make it navigate to the new URL on the current browser/tab
                ele.SetAttribute("target", "_self");
            }
            ele = ele.Parent;
        }
    }
    

    However, do note that these methods don't prevent browser windows from being opened outside your application via JavaScript.

提交回复
热议问题