如何使用.net 2.0中的WebBrowser控件检查ajax更新?

时间:2008-11-10 22:44:11

标签: c# .net ajax winforms

我有一个使用WebBrowser控件在winform应用程序中显示的网页。我需要在网页中的HTML发生变化时执行一个事件;但是,我无法找到通过Ajax更新页面时触发的事件。 DocumentComplete,FileDownloaded和ProgressChanged事件并不总是由Ajax请求触发。我能想到解决问题的唯一方法是轮询文档对象并查找更改;但是,我认为这不是一个很好的解决方案。

是否还有其他一些我将丢失的事件将在ajax更新或其他解决问题的方法上触发?

我正在使用C#和.net 2.0

1 个答案:

答案 0 :(得分:3)

我一直在使用计时器,只是观察特定元素内容的变化。

Private AJAXTimer As New Timer

Private Sub WaitHandler1(ByVal sender As Object, ByVal e As System.EventArgs)
    'Confirm that your AJAX operation has completed.
    Dim ProgressBar = Browser1.Document.All("progressBar")
    If ProgressBar Is Nothing Then Exit Sub

    If ProgressBar.Style.ToLower.Contains("display: none") Then
        'Stop listening for ticks
        AJAXTimer.Stop()

        'Clear the handler for the tick event so you can reuse the timer.
        RemoveHandler AJAXTimer.Tick, AddressOf CoveragesWait

        'Do what you need to do to the page here...

        'If you will wait for another AJAX event, then set a
        'new handler for your Timer. If you are navigating the
        'page, add a handler to WebBrowser.DocumentComplete
    End If
Exit Sub

Private Function InvokeMember(ByVal FieldName As String, ByVal methodName As String) As Boolean
        Dim Field = Browser1.Document.GetElementById(FieldName)
        If Field Is Nothing Then Return False

        Field.InvokeMember(methodName)

        Return True
    End Function

我有2个对象可以获取事件处理程序,WebBrowser和Timer。 我主要依赖WebBrowser上的DocumentComplete事件和Timer上的Tick事件。

我根据需要为每个操作编写DocumentComplete或Tick处理程序,每个处理程序通常都是RemoveHandler本身,因此成功的事件只会被处理一次。我还有一个名为RemoveHandlers的过程,它将从浏览器和计时器中删除所有处理程序。

我的AJAX命令通常如下:

AddHandler AJAXTimer.Tick, AddressOf WaitHandler1
InvokeMember("ContinueButton", "click")
AJAXTimer.Start

我的导航命令如:

AddHandler Browser1.DocumentComplete, AddressOf AddSocialDocComp
Browser1.Navigate(NextURL) 'or InvokeMember("ControlName", "click") if working on a form.
相关问题