C#导航到WebBrowser控件中的Anchors

joh*_*hnc 9 c# webbrowser-control winforms

我们的Winforms应用程序中有一个Web浏览器,可以很好地显示xslt呈现的所选项目的历史记录.

xslt在输出的html中写出<a>标签,以允许webBrowser控件导航到所选的历史条目.

因为我们没有在严格的网络意义上"导航"到html,而是通过DocumentText设置html,所以我无法使用#AnchorName"导航"到所需的锚点,因为webBrowser的Url为null(编辑:实际上是完成它是关于:空白).

在这种情况下,如何动态导航到Web浏览器控件的html中的Anchor标签?

编辑:

感谢sdolphion的提示,这是我使用的最终代码

void _history_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        _completed = true;
        if (!string.IsNullOrEmpty(_requestedAnchor))
        {
            JumpToRequestedAnchor();
            return;
        }
    }

    private void JumpToRequestedAnchor()
    {
        HtmlElementCollection elements = _history.Document.GetElementsByTagName("A");
        foreach (HtmlElement element in elements)
        {
            if (element.GetAttribute("Name") == _requestedAnchor)
            {
                element.ScrollIntoView(true);
                return;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

sdo*_*hin 10

我相信有人有更好的方法可以做到这一点,但这是我用来完成这项任务的方法.

HtmlElementCollection elements = this.webBrowser.Document.Body.All;
foreach(HtmlElement element in elements){
   string nameAttribute = element.GetAttribute("Name");
   if(!string.IsNullOrEmpty(nameAttribute) && nameAttribute == section){
      element.ScrollIntoView(true);
      break;
   }
}
Run Code Online (Sandbox Code Playgroud)


dbo*_*her 5

我知道这个问题很老,而且答案很好,但是还没有提出这个问题,所以对于那些来这里寻找答案的人来说,这可能是有用的.

另一种方法是使用HTML中的元素id.

<p id="section1">This is a test section</p>

然后你可以使用

HtmlElement sectionAnchor = webBrowserPreview.Document.GetElementById("section1");
if (sectionAnchor != null)
{
    sectionAnchor.ScrollIntoView(true);
}
Run Code Online (Sandbox Code Playgroud)

webBrowserPreview是您的WebBrowser控件.

或者,sectionAnchor.ScrollIntoView(false)只会将元素放在屏幕上,而不是将其与页面顶部对齐