How can I get the page title in WebBrowser control?

后端 未结 6 685
挽巷
挽巷 2021-02-13 20:00

How can I get the page title in a WebBrowser control when I navigate to different websites?


xmlns

xmlns:phone=\"clr-namespace:Microsoft.Phone.Contr         


        
6条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 21:02

    For me the following code works. The answers from @Akash and @Mikko set me on the right path, but I still had some problems with a few websites. The problem as I understand it is that the Navigated event is raised when the WebBrowser component starts getting data from the remote server. As such the DOM object is not yet complete, so calling the document.title throws an error. So I just retry after a few milliseconds till I get the title. This "loop" has never iterated more than 3 times on any website I tested and flawlessly brought me the title every time.

    private void webBrowser1_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
    {
        ThreadPool.QueueUserWorkItem(UpdateText);
    }
    
    private void UpdateText(object o)
    {
        Thread.Sleep(100);
        Dispatcher.BeginInvoke(() =>
        {
            try
            {
                textBlock1.Text = webBrowser1.InvokeScript("eval", "document.title").ToString();
            }
            catch (SystemException)
            {
                ThreadPool.QueueUserWorkItem(UpdateText);
            }
        });
    }
    

提交回复
热议问题